我有以下代码,并尝试从外部链接打开 Accordion 面板。我从网站上获取了代码作为示例,到目前为止它运行良好,但我似乎不知道如何执行此操作。
jQuery:
jQuery(document).ready(function() {
function close_accordion_section() {
jQuery('.accordion .accordion-section-title').removeClass('active');
jQuery('.accordion .accordion-section content').slideUp(300).removeClass('open');
}
jQuery('.accordion-section-title').click(function(e) {
// Grab current anchor value
var currentAttrValue = jQuery(this).attr('href');
if(jQuery(e.target).is('.active')) {
close_accordion_section();
}else {
close_accordion_section();
// Add active class to section title
jQuery(this).addClass('active');
// Open up the hidden content panel
jQuery('.accordion ' + currentAttrValue).slideDown(300).addClass('open');
}
e.preventDefault();
});
});
HTML:
<div class="accordion">
<div class="accordion-section">
<a class="accordion-section-title" href="#section-1">Section 1: </a>
<div id="section-1" class="accordion-section-content">
<p>Content goes here</p>
</div><!--end .accordion-section-content-->
</div><!--end .accordion-section-->
<div class="accordion-section">
<a class="accordion-section-title" href="#section-2">Section 2: </a>
<div id="section-2" class="accordion-section-content">
<p>Content goes here</p>
</div><!--end .accordion-section-content-->
</div><!--end .accordion-section-->
到目前为止,我已经尝试过外部链接:
<a href="#section-2.active">Link</a>
...以及一些类似的事情,但不幸的是还没有欢乐。我也摆弄过 jQuery,但也没有取得任何进展。
我对 jQuery 没有太多经验,我正在努力学习它,所以请彻底回答所有问题,以便我可以学习。非常感谢!
最佳答案
当页面加载时,您的 ready
函数将运行,这应该打开 URI 的 hash 的 Accordion 部分。指:
jQuery(document).ready(function() {
// get the #section from the URL
var hash = window.location.hash;
// open accordion
jQuery(hash).slideDown(300).addClass('open');
// set title to active
jQuery(hash).prev('.accordion-section-title').addClass('active');
/* ... the rest of your code here */
});
如果你没有两次获取 jQuery 对象,你可能会获得轻微的性能提升,你可以像这样链接它们:
jQuery(hash).slideDown(300).addClass('open')
.prev('.accordion-section-title').addClass('active');
关于javascript - 从外部链接打开 Accordion 面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505700/