这里有一个漂亮的小手风琴,它使用标题来展开和折叠下面的内容。一切都按照我想要的方式工作,除了一件事:当您通过单击标题展开一个部分时,您应该能够再次单击标题将其折叠。这张照片有什么问题吗?
<script type="text/javascript">
$(document).ready(function(){
$(".haccordion > :header").addClass("h-trigger static").next().addClass("section collapsed").attr("inert","");
document.querySelectorAll('.h-trigger').forEach(el => {
el.setAttribute("tabindex", "0");
el.addEventListener("keydown", e => {
if ([" ", "Enter", "ArrowDown"].includes(e.key)) {
e.target.click();
}
});
});
$(".h-trigger.static").click(function(){
$(this).closest(".haccordion").find(".h-trigger.active").removeClass("active").addClass("static");
$(this).closest(".haccordion").find(".section.expanded").removeClass("expanded").addClass("collapsed").attr("inert","");
$(this).removeClass("static").addClass("active");
$(this).next(".section.collapsed").removeClass("collapsed").addClass("expanded").removeAttr("inert","");
});
$(".h-trigger.active").click(function(){
$(this).removeClass("active").addClass("static");
$(this).next(".section.expanded").removeClass("expanded").addClass("collapsed").attr("inert","");
});
});
</script>
<div class="haccordion">
<h2>Section with a paragraph</h2>
<p>Here is some text content</p>
<h2>Section with a div</h2>
<div>
<h3>Heading</h3>
<p>Here is some content with text and an image</p>
<p><a href="#">Test link</a></p>
</div>
<h2>Section with a list</h2>
<ul>
<li>List item 1</li>
<li>List item 2</li>
</ul>
</div>
$(".h-trigger.active").click
只会将点击处理程序附加到 h-trigger
(即 currently active
)。如果执行此行时没有 active
元素,则 没有元素 接收该单击处理程序。有两种解决方案(实际上,只有一个解决方案;另一个是 jQuery 通过在幕后工作帮助您完成第一个解决方案):
为
.h-trigger
附加一个handler,然后在handler内部手动检查目标元素是否有.static
或.active
,并进行相应处理
使用 jQuery 的 live 处理程序