Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

前端 未结 24 1538
夕颜
夕颜 2020-11-22 04:57

I\'m developing a web page in which I\'m using Twitter\'s Bootstrap Framework and their Bootstrap Tabs JS. It works great except for a few minor issues, one of which is I do

24条回答
  •  长发绾君心
    2020-11-22 05:19

    UPDATE

    For Bootstrap 3, change .on('shown', ...) to .on('shown.bs.tab', ....)


    This is based off of @dubbe answer and this SO accepted answer. It handles the issue with window.scrollTo(0,0) not working correctly. The problem is that when you replace the url hash on tab shown, the browser will scroll to that hash since its an element on the page. To get around this, add a prefix so the hash doesn't reference an actual page element

    // Javascript to enable link to tab
    var hash = document.location.hash;
    var prefix = "tab_";
    if (hash) {
        $('.nav-tabs a[href="'+hash.replace(prefix,"")+'"]').tab('show');
    } 
    
    // Change hash for page-reload
    $('.nav-tabs a').on('shown', function (e) {
        window.location.hash = e.target.hash.replace("#", "#" + prefix);
    });
    

    Example of use

    If you have tab-pane with id="mytab" you need to put your link like this:

    Go to Specific Tab 
    

提交回复
热议问题