[英]How to detect proper element to show based on the anchor within the element?
我在页面上使用了多个Twitter Bootstrap折叠组。 每个组可能包含几个锚点:
<div class="accordion" id="accordion">
<div class="accordion-group">
<div class="accordion-heading"> <a href="#section1"></a><a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Section 1</a>
</div>
<div id="collapseOne" class="accordion-body collapse">
<div class="accordion-inner">
<p><a href="#section1-text1"></a>Section 1 - Text 1</p>
<p><a href="#section1-text2"></a>Section 1 - Text 2</p>
</div>
</div>
</div>
<div class="accordion-group">
<div class="accordion-heading"> <a href="#section2"></a><a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">Section 2</a>
</div>
<div id="collapseTwo" class="accordion-body collapse">
<div class="accordion-inner">
<p><a href="#section2-text1"></a>Section 2 - Text 1</p>
<p><a href="#section2-text2"></a>Section 2 - Text 2</p>
</div>
</div>
</div>
</div>
如果我的页面是用URL中的特定哈希值打开的(例如http://example.com#section2-text2
),则应显示相应的折叠。 我打算使用window.location.hash
来了解显示哪个折叠( jsfiddle ):
var hash = window.location.hash;
if (hash == '#collapseOne' || hash == '#collapseTwo') {
$(hash).collapse('show');
}
但是我有两个问题:
somethingelse-text2
,即不包含section2
); 如何找到锚somethingelse-text2
parent
折叠元素? 对于问题的第一部分,您可以使用类似以下的内容:
var hash = window.location.hash;
if(hash){
var targetAnchor = $(hash + ",a[href='"+hash+"']");
if(targetAnchor.length > 0){
targetAnchor.closest(".collapse").collapse('show');
}
}
对于第二部分,浏览器通常是本机执行的,但是在您的情况下,我很确定它不会发生,因为锚点隐藏在折叠块内。 如果是这样,您可以像这样手动滚动:
$('html, body').animate({
scrollTop: targetAnchor.offset().top
}, 2000);
基于这个答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.