如何创建:折叠效果
学习如何创建可折叠部分。
可折叠效果
单击该按钮可在显示和隐藏可折叠内容之间切换。
Some collapsible content. Click the button to toggle between showing and hiding the collapsible content. 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; }
第三步 - 添加 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: '\02795'; /* 表示“加号”(+)的 Unicode 字符 */ font-size: 13px; color: white; float: right; margin-left: 5px; } .active:after { content: "\2796"; /* 表示“减号”(-)的 Unicode 字符 */ }