我在解决WordPress站点上的JavaScript折叠菜单问题时遇到了问题。当单击accordion按钮时,它不会显示隐藏在它下面的内容。我尝试了许多解决方案,它们要么不起作用,要么超出了我的能力范围。我是一个初学者,这可能是一个简单的修复方法,但我已经在这个问题上挣扎了几天。下面是我的代码:
JavaScript:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
}
CSS:
/* Style the buttons that are used to open and close the accordion panel */
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
outline: none;
transition: 0.4s;
}
/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.active, .accordion:hover {
background-color: #ccc;
}
/* Style the accordion panel. Note: hidden by default */
.panel {
padding: 0 18px;
background-color: white;
display: none;
overflow: hidden;
}
HTML:
<button class="accordion">Section 1</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>
根据FireFox的说法,令人不快的代码片段是if (panel.style.display === "block") {
,它抛出一个TypeError: panel is null
异常。我已经用alert('hi');
测试了我的页面,它工作得很好,所以我认为JavaScript正在加载。
发布于 2018-08-05 08:25:48
我将你的代码添加到一个jsfiddle中,它似乎工作得很好,两个按钮都显示了隐藏的内容。
https://jsfiddle.net/pnuyLhbq/1/
因此,如果添加另一个折叠按钮,当前代码就没问题了
<button class="accordion">Section 1</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>
<button class="accordion">Section 2</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>
https://stackoverflow.com/questions/51689828
复制相似问题