سؤال

I use a number of Twitter Bootstrap collapse groups on my page. Each group may contain several anchors:

<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> 

If my page is opened with particular hash in the URL (like http://example.com#section2-text2), then according collapse should shown. I am planning to use window.location.hash to understand which collapse to show (jsfiddle):

  var hash = window.location.hash;
  if (hash == '#collapseOne' || hash == '#collapseTwo') {
    $(hash).collapse('show');
  }

But I have two questions:

  1. how to identify proper collapse to show if hash doesn't contain it is name (for ex., anchor and hash are somethingelse-text2, i.e. doesn't contain section2); how to find parent collapse element of the anchor somethingelse-text2?
  2. should I scroll manually to the anchor after collapse showing?
هل كانت مفيدة؟

المحلول

For the first part of your question you can use something like this:

var hash = window.location.hash;
if(hash){
    var targetAnchor = $(hash + ",a[href='"+hash+"']");
    if(targetAnchor.length > 0){
        targetAnchor.closest(".collapse").collapse('show');
    }   
}

For the second part, browsers usually do this natively, but in your case i'm pretty sure its not going to happen because the anchor is hidden inside your collapse block. If so, you can scroll manually like this:

$('html, body').animate({
    scrollTop: targetAnchor.offset().top
}, 2000);

Based on this answer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top