Accordion在我的HTML页面中没有按预期工作



我试图在我的HTML页面中添加手风琴,它根本不起作用。我不确定我是否整合正确版本的js (jquery-3.6.0.min.js)。我要导入别的东西吗?我想不明白。这是我的代码:

index . html

<button class="accordion">Section 1</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>

index.js

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}

同样,我按照这个W3S页面一步一步地操作,但没有发现任何问题。

如果您正在使用jQuery(就像您提到的),您可以使用.slideToggle方法(https://api.jquery.com/slidetoggle/)。下面是一个示例,它还使用了一些其他方便的jQuery方法:

$(".accordion").click(function() {
$(this).next().slideToggle();
});

下面是CodePen上的一个工作示例:https://codepen.io/andyranged/pen/16a51bb5f076bf2348023c000ce7ded0

那非常w3schools - How TO - Collapsibles/Accordion将无法正常工作,如果你不分配max-height给<div class="panel">:

CSS:

.panel {
max-height: 0;
}

最新更新