作成方法:折りたたみ効果
- 前のページ ポップアップウィンドウ
- 次のページ カレンダー
可折りたたみ部分の作成方法を学習します。
可折畳効果
このボタンをクリックすると、可折畳コンテンツの表示と非表示を切り替えます。
一部可折畳コンテンツがあります。ボタンをクリックして、可折畳コンテンツの表示と非表示を切り替えます。Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
创建可折叠部分效果
第一步 - 添加 HTML:
<button type="button" class="collapsible">Open Collapsible</button> <div class="content"> <p>Lorem ipsum...</p> </div>
第二步 - 添加 CSS:
设置手风琴样式:
/* 设置用于打开和关闭可折叠内容的按钮的样式 */ .collapsible { background-color: #eee; color: #444; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; } /* 当按钮被点击时,以及当您将鼠标移到按钮上时(悬停),为按钮添加背景颜色(使用 JS 添加 .active 类) */ .active, .collapsible:hover { background-color: #ccc; } /* 设置可折叠内容的样式。注意:默认隐藏 */ .content { padding: 0 18px; display: none; overflow: hidden; background-color: #f1f1f1; }
第3步 - 添加 JavaScript:
var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } }); }
アニメーション付きの折り畳み効果(下にスライド)
アニメーション付きの折り畳み効果を作成するには、以下を設定します: max-height: 0
、overflow: hide
および max-height
属性のトランジションをパネルクラスに追加します。
次に、JavaScript を使用して計算された max-height
コンテンツを下にスライドするには、パネルの異なるスクリーンサイズに応じて具体的に以下の高さを設定します:
例
<style> .content { padding: 0 18px; background-color: white; max-height: 0; overflow: hidden; transition: max-height 0.2s ease-out; } </style> <script> var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.maxHeight){ content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + "px"; } }); } </script>
アイコンを追加
各ボタンにシンボルを追加して、折り畳み可能なコンテンツが開かれているか閉じているかを示します:
例
.collapsible:after { content: "・"; /* 表示「プラス」の Unicode 文字 */ font-size: 13px; color: white; float: right; margin-left: 5px; } .active:after { content: "・"; /* 表示「マイナス」の Unicode 文字 */ }
- 前のページ ポップアップウィンドウ
- 次のページ カレンダー