我有一个默认关闭 Accordion 功能的页面,并在单击内容时打开,如箭头所示。我在页面的最顶部有一个链接,我希望它跳转到 Accordion 内容的特定部分并打开它。由于我的 Javascript 知识非常有限,我很难让它工作!它目前什么都不做。任何帮助,将不胜感激。
我尝试了页面顶部的 anchor 链接,该链接跳转到包含内容的 Accordion 区域,但我不确定接下来要尝试什么才能打开内容部分。
这是我希望在单击时锚定和打开 Accordion 内容的初始链接:
<p class="text_center">
We've made some changes to our Privacy Policy -
<a href="#updates" style="color:red; text-decoration:none;">
<span style="color:red;">
<strong>click here</strong>
to see the changes
</span>
</a>
</p>
这是单击链接时我想打开的 Accordion 部分:
<div class="about-panel2" id="updates">
这是“about-panel2”的 CSS:
.about-panel2 {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
这是脚本:
<script>
var acc = document.getElementsByClassName("about-accordion2");
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";
}
});
}
</script>
单击时,页面会尝试跳转到内容,但 Accordion 不显示。我知道我需要修改(?)脚本才能完成这项工作,但我不知道下一步该做什么!任何帮助将不胜感激。提前致谢。
最佳答案
您可以通过单击该链接将 active
类添加到 Accordion 中来实现。
例子:
添加点击事件
<p class="text_center">
We've made some changes to our Privacy Policy -
<a href="#updates" style="color:red; text-decoration:none;" onclick="openAccordian('updates')">
<span style="color:red;">
<strong>click here</strong>
to see the changes
</span>
</a>
</p>
在脚本中添加一个函数
<script>
function openAccordian(id) {
document.getElementById(id).classList.toggle("active");
}
</script>
关于javascript - 单击同一页面中的链接时如何打开 Accordion 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954851/