Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - Bootstrap 3 expand accordion from URL

Using Bootstrap 3, I'm trying to use sub-navigation anchor links (ie, index.php#wnsh) to expand a specified accordion and anchor down the page to the content. I've tried searching for examples but with little luck, likely because my accordion structure is different from the given BS3 example. Here's my HTML:

UPDATE:

Made a few updates to the code, but it still isn't opening the accordion specified by the hash. Any further thoughts?

            <div id="accordion" class="accordion-group">                
                <div class="panel">
                    <h4 id="cs" class="accordion-title"><a data-toggle="collapse" data-parent="#accordion" data-target="#cs_c">Child Survival: Boosting Immunity and Managing Diarrhoea</a></h4>
                    <div id="cs_c" class="accordion-collapse collapse in">
                        <p>...</p>
                    </div>

                    <h4 id="chgd" class="accordion-title"><a data-toggle="collapse" data-parent="#accordion" data-target="#chgd_c">Child Health, Growth and Development: Preventing Mental Impairment with Iodine and Iron</a></h4>
                    <div id="chgd_c" class="accordion-collapse collapse">
                        <p>...</p>
                    </div>

                    <h4 id="wmnh" class="accordion-title"><a data-toggle="collapse" data-parent="#accordion" data-target="#wmnh_c">Women’s and Newborn Survival and Health: Iron Supplementation and Food Fortification</a></h4>
                    <div id="wmnh_c" class="accordion-collapse collapse">
                        <p>...</p>
                    </div>
                </div>
            </div>

JS

var elementIdToScroll =  window.location.hash;

if(window.location.hash != ''){
  $("#accordion .in").removeClass("in");
  $(elementIdToScroll).addClass("in");
   $('html,body').animate({scrollTop: $(elementIdToScroll).offset().top},'slow');
}

Thanks in advance. Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Tested and working in Bootstrap 3.3.5.

<script type="text/javascript">
$(document).ready(function () {
    if(location.hash != null && location.hash != ""){
        $('.collapse').removeClass('in');
        $(location.hash + '.collapse').collapse('show');
    }
});
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...