首页 文章

Twitter Bootstrap选项卡:转到页面重新加载或超链接上的特定选项卡

提问于
浏览
313

我'm developing a web page in which I'使用Twitter的Bootstrap框架和他们的Bootstrap Tabs JS . 除了一些小问题外,它的效果很好,其中一个是我不知道如何直接从外部链接转到特定的选项卡 . 例如:

<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>

应分别转到“主页”选项卡和“注释”选项卡 when clicked on the links from an external page

22 回答

  • 204

    我建议你使用Bootstrap作者提供的代码issue tracker on GitHub

    var hash = location.hash
      , hashPieces = hash.split('?')
      , activeTab = $('[href=' + hashPieces[0] + ']');
    activeTab && activeTab.tab('show');
    

    您可以在问题的链接上找到有关他们为什么不选择支持该问题的更多信息 .

  • 10

    虽然提供的JavaScript解决方案可能有效,但我采用了略微不同的方式,不需要额外的JavaScript,但在视图中需要逻辑 . 您可以使用标准URL参数创建链接,例如:

    <a href = "http://link.to.yourpage?activeTab=home">My Link</a>
    

    然后你只需检测activeTab的值,在相应的 <li> 中写入'class= 238695 '

    伪代码(用你的语言相应地实现) . 注意如果此示例中未提供参数,我将“home”选项卡设置为默认活动 .

    $activetabhome = (params.activeTab is null or params.activeTab == 'home') ? 'class="active"' : '';
    $activetabprofile = (params.activeTab == 'profile') ? 'class="active"' : '';
    
    <li $activetabhome><a href="#home">Home</a></li>
    <li $activetabprofile><a href="#profile">Profile</a></li>
    
  • 3

    您可以在相应的标签链接上触发 click 事件:

    $(document).ready(function(){
    
      if(window.location.hash != "") {
          $('a[href="' + window.location.hash + '"]').click()
      }
    
    });
    
  • 3

    这可以在Bootstrap 3中运行,并通过集成GarciaWebDev的答案来改进dubbe和flynfish的2个最佳答案(它允许在哈希之后的url参数,并且直接来自github问题跟踪器上的Bootstrap作者):

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

    此代码根据#hash选择正确的选项卡,并在单击选项卡时添加正确的#hash . (这使用jquery)

    在Coffeescript中:

    $(document).ready ->
        if location.hash != ''
            $('a[href="'+location.hash+'"]').tab('show')
    
        $('a[data-toggle="tab"]').on 'shown', (e) ->
            location.hash = $(e.target).attr('href').substr(1)
    

    或者在JS中:

    $(document).ready(function() {
        if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');
        return $('a[data-toggle="tab"]').on('shown', function(e) {
          return location.hash = $(e.target).attr('href').substr(1);
        });
    });
    
  • 5

    我不得不修改一些内容,以便为我工作 . 我正在使用Bootstrap 3和jQuery 2

    // Javascript to enable link to tab
    var hash = document.location.hash;
    var prefix = "!";
    if (hash) {
        hash = hash.replace(prefix,'');
        var hashPieces = hash.split('?');
        activeTab = $('[role="tablist"] a[href=' + hashPieces[0] + ']');
        activeTab && activeTab.tab('show');
    }
    
    // Change hash for page-reload
    $('[role="tablist"] a').on('shown.bs.tab', function (e) {
        window.location.hash = e.target.hash.replace("#", "#" + prefix);
    });
    
  • 18

    对于Bootstrap 3:

    $('.nav-tabs a[href="#' + tabID + '"]').tab('show');
    

    https://jsfiddle.net/DTcHh/6638/

  • 37

    这是我做的,非常简单,如果您的标签链接有一个与之关联的ID,您可以获取href属性并将其传递给显示标签内容的函数:

    <script type="text/javascript">
            jQuery(document).ready(function() {
                var hash = document.location.hash;
                var prefix = "tab_";
                if (hash) {
                    var tab = jQuery(hash.replace(prefix,"")).attr('href');
                    jQuery('.nav-tabs a[href='+tab+']').tab('show');
                }
            });
            </script>
    

    然后在您的网址中,您可以添加哈希,例如:#tab_tab1,'tab_'部分将从哈希本身中删除,因此导航标签(tabid1)中的实际标签链接的ID将放在此之后,因此您的url看起来像:www.mydomain.com/index.php#tab_tabid1 .

    这对我来说很完美,希望它可以帮助别人:-)

  • 3

    以Demircan Celebi的解决方案为基础;我希望在修改URL和打开选项卡时打开选项卡,而无需从服务器重新加载页面 .

    <script type="text/javascript">
        $(function() {
            openTabHash(); // for the initial page load
            window.addEventListener("hashchange", openTabHash, false); // for later changes to url
        });
    
    
        function openTabHash()
        {
            console.log('openTabHash');
            // 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
                }
            })
        }
    </script>
    
  • 8

    这是dubbe解决方案的改进实现,可防止滚动 .

    // 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
        }
    })
    
  • 2

    感谢您分享您的观点 .

    通过阅读所有解决方案 . 我想出了一个使用url hash或localStorage的解决方案,具体取决于后者的可用性,代码如下:

    $(function(){
        $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
            localStorage.setItem('activeTab', $(e.target).attr('href'));
        })
    
        var hash = window.location.hash;
        var activeTab = localStorage.getItem('activeTab');
    
        if(hash){
              $('#project-tabs  a[href="' + hash + '"]').tab('show');   
        }else if (activeTab){
            $('#project-tabs a[href="' + activeTab + '"]').tab('show');
        }
    });
    
  • 1

    尝试了上面讨论过的几种方法并最终得到以下工作解决方案,只需复制并粘贴到您的编辑器中即可尝试 . 要测试只是更改哈希到收件箱,发件箱,在网址中撰写并点击回车键 .

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

    希望这会节省你的时间 .

  • 43

    结合其他答案中的peices,这是一个可以打开多层嵌套选项卡的解决方案:

    // opens all tabs down to the specified tab
    var hash = location.hash.split('?')[0];
    if(hash) {
      var $link = $('[href=' + hash + ']');
      var parents = $link.parents('.tab-pane').get();
      $(parents.reverse()).each(function() {
        $('[href=#' + this.id + ']').tab('show') ;
      });
      $link.tab('show');
    }
    
  • 8
    $(function(){
      var hash = window.location.hash;
      hash && $('ul.nav a[href="' + hash + '"]').tab('show');
    });
    

    来自http://github.com/twitter/bootstrap/issues/2415#issuecomment-4450768的代码完美地为我工作 .

  • 4

    我刚遇到这个问题,但需要处理多个标签级别 . 代码相当丑陋(见评论),但它的工作:https://gist.github.com/JensRantil/4721860希望其他人会发现它有用(并随意提出更好的解决方案!) .

  • 0

    如果它对任何人都很重要,那么以下代码很小并且完美无瑕,从URL获取单个哈希值并显示:

    <script>
        window.onload = function () {
            let url = document.location.toString();
            let splitHash = url.split("#");
            document.getElementById(splitHash[1]).click();
        };
    </script>
    

    它的作用是检索id并触发click事件 . 简单 .

  • 2

    这是我对问题的解决方案,也许有点晚了 . 但它可能有助于其他人:

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

    这是我处理嵌套选项卡的解决方案 . 我刚添加了一个函数来检查活动选项卡是否有要激活的父选项卡 . 这是功能:

    function activateParentTab(tab) {
        $('.tab-pane').each(function() {
            var cur_tab = $(this);
            if ( $(this).find('#' + tab).length > 0 ) {
                $('.nav-tabs a[href=#'+ cur_tab.attr('id') +']').tab('show');
                return false;
            }
        });
    }
    

    并且可以这样调用(基于@ flynfish的解决方案):

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

    这个解决方案目前对我来说非常好 . 希望这对其他人有用;)

  • 5

    如果......别的话我不是很喜欢的;所以我采取了一种更简单的方法 .

    $(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;
        })
    });
    
    • 选择默认选项卡(通常是第一个)

    • 切换到选项卡(如果确实存在这样的元素;让jQuery处理它);如果指定了错误的哈希,则没有任何反应

    • [可选]如果手动选择了另一个选项卡,则更新哈希

    不解决滚动到请求的哈希;但 should 呢?

  • 531

    对于ajax #!# (例如/test.com#!#test3)的链接我这样做,但你可以修改它,无论你喜欢什么

    $(document).ready(function() {
    
           let hash = document.location.hash;
           let prefix = "!#";
    
           //change hash url on page reload
           if (hash) {
             $('.nav-tabs a[href=\"'+hash.replace(prefix,"")+'\"]').tab('show');
           } 
    
           // change hash url on switch tab
           $('.nav-tabs a').on('shown.bs.tab', function (e) {
              window.location.hash = e.target.hash.replace("#", "#" + prefix);
           });
     });
    

    简单页面示例on Github here

  • 0

    UPDATE

    对于Bootstrap 3,将 .on('shown', ...) 更改为 .on('shown.bs.tab', ....)


    这基于@dubbe回答和SO accepted answer . 它处理 window.scrollTo(0,0) 无法正常工作的问题 . 问题是当你替换显示的标签上的url hash时,浏览器将滚动到该哈希,因为它是页面上的一个元素 . 要解决此问题,请添加前缀,以使哈希不引用实际的页面元素

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

    如果你有id =“mytab”的标签窗格,你需要把你的链接放在这样的:

    <a href="yoursite.com/#tab_mytab">Go to Specific Tab </a>
    
  • 6

    我用于嵌套标签的@flynfish @Ztyx解决方案:

    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);
                }
            });
        }
    

    孩子们应该有class =“nested”

相关问题