[英]How to open part of an accordion when clicking on a link in the same page
我有一個默認情況下關閉的具有手風琴功能的頁面,並在單擊內容時打開該頁面,如箭頭所示。 我在頁面頂部有一個鏈接,我希望它跳到手風琴內容的特定部分並打開它。 由於我的Javascript知識非常有限,因此很難使它起作用! 目前沒有任何作用。 任何幫助,將不勝感激。
我已經嘗試了頁面頂部的錨鏈接,該鏈接跳至包含內容的手風琴區域,但是我不確定下一步該怎么做才能打開內容部分。
這是單擊時我想錨定並打開手風琴內容的初始鏈接:
<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>
這是單擊鏈接時我想打開的手風琴部分:
<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>
單擊時,頁面嘗試跳至內容,但手風琴未顯示。 我知道我需要修改(?)腳本才能完成此工作,但是我不知道下一步該怎么做! 任何幫助將不勝感激。 提前致謝。
您可以通過單擊該鏈接將active
類添加到該手風琴中來實現。
例:
添加onClick事件
<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>
嗨,雷切爾,歡迎來到SO。
為此,您需要插入少量JS
var hash = window.location.hash;
var anchor = $('a[href$="'+hash+'"]');
if (anchor.length > 0){
anchor.click();
}
這允許從外部鏈接打開手風琴。 有關更詳細的示例和說明,請訪問本教程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.