面板"/>
js折叠面板
前言:若需要增删面板的(标题和内容),在js的obj对象里面更改。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style>
.accordion {
background-color: #f7f8fc;
color: #5669bd;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
}
.active,.accordion:hover {
background-color: #cccff8;
}
.panel {
padding: 0 18px;
background-color: #e2eefa;
max-height: 0;
overflow: hidden;
transition: max-height 0.4s ease-out;
}
.accordion:after {
content: '\2192';
color: #63a3ec;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2193";
}
.centre{
box-shadow: 0px 0px 5px #888888;
}
</style>
</head>
<body>
<p>折叠面板</p>
<script>
window.onload = ()=> {
const obj = {//自定义更改标题和内容
text_one: '第一个面板标题',
text_two: '第二个面板标题',
text_three: '第三个面板标题',
text_four: '第四个面板标题',
content_one: '第一个面板内容',
content_two: '第二个面板内容',
content_three: '第三个面板内容',
content_four: '第四个面板内容',
}
function init() {
const b = [];
for (const key in obj) {
b.push(obj[key]);
}
let dialogHtml = "";
dialogInstance = document.createElement("div");//创建一个div
dialogInstance.classList.toggle("centre")
for (let i = 0; i < b.length / 2; i++) {
dialogHtml += `<button class="accordion">${b[i]}</button><div class="panel"><p>${b[i + 4]}</p></div>`;
}
dialogInstance.innerHTML = dialogHtml;
document.body.appendChild(dialogInstance);
}
function onbtn(){
let acc = document.getElementsByClassName("accordion");
for (let i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function () {
this.classList.toggle("active");//如果classList中存在给定的值,删除它,否则,添加它;
var panel = this.nextElementSibling;// 属性只返回元素节点之后的兄弟元素节点(不包括文本节点、注释节点)
if (panel.style.maxHeight == 0) {
panel.style.maxHeight = panel.scrollHeight + "px";
} else {
panel.style.maxHeight = null;//该元素的像素高度
}
});
}
}
init();
onbtn();
}
</script>
</body>
</html>
更多推荐
js折叠面板
发布评论