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

mra*_*iks 343 html javascript tabs twitter-bootstrap

我正在开发一个网页,其中我正在使用Twitter的Bootstrap Framework和他们的Bootstrap Tabs JS.除了一些小问题外,它的效果很好,其中一个是我不知道如何从外部链接直接转到特定的选项卡.例如:

<a href="facility.php#home">Home</a>
<a href="facility.php#notes">Notes</a>
Run Code Online (Sandbox Code Playgroud)

单击外部页面上的链接时,应分别转到"主页"选项卡和"注释"选项卡

dub*_*bbe 578

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

// 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;
})
Run Code Online (Sandbox Code Playgroud)

  • 我再添加1行'window.scrollTo(0,0);`以确保Window始终滚动到顶部 (81认同)
  • 对于bootstrap 3,我改变了('显示'...)到on('shown.bs.tab'...),它对我有用. (32认同)
  • 使用window.location.hash (20认同)
  • 这是Bootstrap 3的演示:http://www.bootply.com/render/VQqzOawoYc#tab2和[源代码](http://www.bootply.com/VQqzOawoYc) (10认同)
  • @BillLeeper我刚刚发布了一个处理滚动问题的答案,以防您仍然想知道. (4认同)
  • 将jquery从1.09升级到1.11后,我收到此错误:`语法错误,无法识别的表达式:.nav-tabs a [href =#tab-2]`.使用http://stackoverflow.com/questions/12131273/twitter-bootstrap-tabs-url-doesnt-change解决 (2认同)

fly*_*ish 208

UPDATE

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


这是基于@dubbe答案和这个SO接受的答案.它处理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);
});
Run Code Online (Sandbox Code Playgroud)

使用示例

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

<a href="yoursite.com/#tab_mytab">Go to Specific Tab </a>
Run Code Online (Sandbox Code Playgroud)

  • 对于bootstrap 3,我改变了('显示'...)到on('shown.bs.tab'...)并且它对我有效. (9认同)
  • 是否有一种简单的方法来引用位于特定选项卡下的书签?我的页面上有五个选项卡,在这些选项卡下有许多书签。我想要的是使这些书签可以从选项卡外部链接。 (2认同)

Mar*_*sen 51

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

$(document).ready(function(){

  if(window.location.hash != "") {
      $('a[href="' + window.location.hash + '"]').click()
  }

});
Run Code Online (Sandbox Code Playgroud)


Dem*_*ebi 42

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
    }
})
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 18

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

<a href = "http://link.to.yourpage?activeTab=home">My Link</a>
Run Code Online (Sandbox Code Playgroud)

然后你只需检测activeTab的值,在适当的位置写'class ="active"' <li>

伪代码(用你的语言相应地实现).注意如果此示例中未提供参数,我将"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>
Run Code Online (Sandbox Code Playgroud)


Raz*_*aul 10

对于Bootstrap 3:

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

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


小智 9

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

$(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;
    })
});
Run Code Online (Sandbox Code Playgroud)
  1. 选择默认选项卡(通常是第一个)
  2. 切换到选项卡(如果确实存在这样的元素;让jQuery处理它); 如果指定了错误的哈希,则没有任何反应
  3. [可选]如果手动选择另一个选项卡,则更新哈希

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


gre*_*vis 7

这部作品在引导3和"通过整合GarciaWebDev第2个答案的答案,以及(它允许散列后的URL参数,是直接从GitHub的问题跟踪引导作者)提高dubbe和flynfish:

// 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);
});
Run Code Online (Sandbox Code Playgroud)


Ami*_*ian 7

只需在您的页面上插入以下代码:

$(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);
  });
});
Run Code Online (Sandbox Code Playgroud)


Suc*_*oir 6

此代码根据#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)
Run Code Online (Sandbox Code Playgroud)

或者在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);
    });
});
Run Code Online (Sandbox Code Playgroud)


Gav*_*vin 6

以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>
Run Code Online (Sandbox Code Playgroud)


tom*_*bak 5

$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav a[href="' + hash + '"]').tab('show');
});
Run Code Online (Sandbox Code Playgroud)

来自http://github.com/twitter/bootstrap/issues/2415#issuecomment-4450768的代码对我来说非常有用.


Art*_*hin 5

我用于嵌套标签的@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);
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

孩子们应该有class ="嵌套"


小智 5

感谢您分享您的观点.

通过阅读所有解决方案.我想出了一个使用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');
    }
});
Run Code Online (Sandbox Code Playgroud)