如何使用CSS和JavaScript创建可折叠的部分
可折叠的部分是一种通过点击可以展开和收缩内容的部分。它们是一种常见的组织内容的方式,用户只有在需要时才能查看某一部分的内容。在本文中,我们将学习如何使用CSS和JavaScript创建一个简单的可折叠部分。
方法: 通过使用按钮并将部分的内容放入一个div中来实现。将事件监听器添加到按钮上以监听鼠标点击。每次点击按钮时,切换“Active”类。当部分展开时,按钮的背景颜色会改变。此外,当点击按钮时,“content”的“display”属性会从“none”(隐藏)更改为“block”,从而使内容可见,反之亦然,如下所示。
示例1: 此示例展示了上述解释的方法的使用。
<head>
<style>
.collapse {
background-color: #a2de96;
border: none;
outline: none;
font-size: 25px;
}
.active,
.collapse:hover {
background-color: #438a5e;
}
.text {
background-color: #e1ffc2;
display: none;
font-size: 20px;
}
</style>
<head>
<body>
<h1 style="color:green">GeeksforGeeks</h1>
<button type="button" class="collapse">
Open Collapsible section
</button>
<div class="text">
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and ...
</div>
<script>
var btn = document.getElementsByClassName("collapse");
btn[0].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";
}
});
</script>
</body>
输出:
示例2: 折叠按钮和内容的“宽度”设置为50%,内容“居中”对齐。
<head>
<style>
.collapse {
background-color: #a2de96;
border: none;
outline: none;
font-size: 25px;
}
.active,
.collapse:hover {
background-color: #438a5e;
}
.text {
background-color: #e1ffc2;
display: none;
font-size: 20px;
}
</style>
</head>
<body>
<h1 style="color:green">GeeksforGeeks</h1>
<button type="button" class="collapse">
Open Collapsible section
</button>
<div class="text">
How to create a collapsible
section using CSS and JavaScript?
</div>
<script>
var btn = document
.getElementsByClassName("collapse");
btn[0].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";
}
});
</script>
</body>
输出: