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

前端 未结 24 1513
夕颜
夕颜 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:14

    This is an improved implementation of dubbe's solution which prevent scrolling.

    // Javascript to enable link to tab
    var url = document.location.toString();
    if (url.match('#')) {
        $('.nav-tabs a[href="#'+url.split('#')[1]+'"]').tab('show') ;
    } 
    
    // With HTML5 history API, we can easily prevent scrolling!
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        if(history.pushState) {
            history.pushState(null, null, e.target.hash); 
        } else {
            window.location.hash = e.target.hash; //Polyfill for old browsers
        }
    })
    
    0 讨论(0)
  • 2020-11-22 05:14

    Tried couple of ways discussed above and end up with following working solution, just copy and paste in your editor to try. To test just change hash to inbox, outbox, compose in url and hit enter key.

    <html>
        <head>
            <link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
            <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
        </head>
        <body>
            <div class="container body-content">
                <ul class="nav nav-tabs">
                    <li class="active"><a data-toggle="tab" href="#inbox">Inbox</a></li>
                    <li><a data-toggle="tab" href="#outbox">Outbox</a></li>
                    <li><a data-toggle="tab" href="#compose">Compose</a></li>
                </ul>
                <div class="tab-content">
                    <div id="inbox" class="tab-pane fade in active">
                        Inbox Content
                    </div>
                    <div id="outbox" class="tab-pane fade">
                        Outbox Content
                    </div>
                    <div id="compose" class="tab-pane fade">
                        Compose Content
                    </div>
                </div>
            </div>
            <script>
                $(function () {
                    var hash = window.location.hash;
                    hash && $('ul.nav a[href="' + hash + '"]').tab('show');
                });
            </script>
        </body>
    </html>
    

    Hope this will save your time.

    0 讨论(0)
  • 2020-11-22 05:14

    Just insert this code on your page:

    $(function(){
      var hash = window.location.hash;
      hash && $('ul.nav a[href="' + hash + '"]').tab('show');
    
      $('.nav-tabs a').click(function (e) {
        $(this).tab('show');
        var scrollmem = $('body').scrollTop();
        window.location.hash = this.hash;
        $('html,body').scrollTop(scrollmem);
      });
    });

    0 讨论(0)
  • 2020-11-22 05:18

    I am not a big fan of if...else; so I took a simpler approach.

    $(document).ready(function(event) {
        $('ul.nav.nav-tabs a:first').tab('show'); // Select first tab
        $('ul.nav.nav-tabs a[href="'+ window.location.hash+ '"]').tab('show'); // Select tab by name if provided in location hash
        $('ul.nav.nav-tabs a[data-toggle="tab"]').on('shown', function (event) {    // Update the location hash to current tab
            window.location.hash= event.target.hash;
        })
    });
    
    1. Pick a default tab (usually the first)
    2. Switch to tab (if such an element is indeed present; let jQuery handle it); Nothing happens if a wrong hash is specified
    3. [Optional] Update the hash if another tab is manually chosen

    Doesn't address scrolling to requested hash; but should it?

    0 讨论(0)
  • 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:

    <a href="yoursite.com/#tab_mytab">Go to Specific Tab </a>
    
    0 讨论(0)
  • 2020-11-22 05:20

    @flynfish + @Ztyx solution that I use for nested tabs:

        handleTabLinks();
    
        function handleTabLinks() {
            if(window.location.hash == '') {
                window.location.hash = window.location.hash + '#_';
            }
            var hash = window.location.hash.split('#')[1];
            var prefix = '_';
            var hpieces = hash.split('/');
            for (var i=0;i<hpieces.length;i++) {
                var domelid = hpieces[i].replace(prefix,'');
                var domitem = $('a[href=#' + domelid + '][data-toggle=tab]');
                if (domitem.length > 0) {
                    domitem.tab('show');
                }
            }
            $('a[data-toggle=tab]').on('shown', function (e) {
                if ($(this).hasClass('nested')) {
                    var nested = window.location.hash.split('/');
                    window.location.hash = nested[0] + '/' + e.target.hash.split('#')[1];
                } else {
                    window.location.hash = e.target.hash.replace('#', '#' + prefix);
                }
            });
        }
    

    childrens should have class="nested"

    0 讨论(0)
提交回复
热议问题