您好,所以我试图设置“显示隐藏”按钮,但由于某种原因,它似乎不起作用。我不确定是什么问题,所以请帮帮我。
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
button.accordion {
background-color: #a5d424;
color: #444;
cursor: pointer;
padding: 10px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-family:"Comic Sans MS", cursive, sans-serif;
font-size: 16px;
transition: 0.4s;
}
button.accordion.active, button.accordion:hover {
background-color: #2d4005;
color: #7FFF00;
}
button.accordion:after {
content: '\25BC'; /*02795*/
font-size: 18px;
color: #777;
float: right;
margin-left: 5px;
}
button.accordion.active:after {
content: "\25B2"; /*02796*/
color: #7FFF00;
}
div.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: 0.6s ease-in-out;
opacity: 0;
}
div.panel.show {
opacity: 1;
max-height: 500px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<button class="accordion"> Button to see panel. <button>
<div class="panel">
<p>TEST</p>
</div>
<!-- <script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
</script> -->
</body>
</html>
答案 0 :(得分:0)
您在html结构中有错误。您尚未关闭“按钮”标签。更改<button> to </button>
,一切正常!
答案 1 :(得分:-1)
您忘记了关闭HTML代码中的button
标签。应该是<button class="accordion"> Button to see panel. </button>
。
顺便说一句,我看到您在HTML中导入了jQuery,但是在JS代码中使用香草JS进行DOM操作。并不是真正的问题,但是DOM操作是jQuery的强项之一,因此您可以再次检查以查看是否确实需要此插件,或者只是将其删除。