在URL链接的基础上激活Bootstrap选项卡

Q-b*_*art 9 jquery tabs twitter-bootstrap

我有引导标签,我想在URL链接的基础上激活标签.

例如:

xyz.xxx/index#tab2应该在页面加载时激活tab2.

到目前为止,这是我的代码

<div class="tab-wrap">
  <div class="parrent pull-left">
    <ul class="nav nav-tabs nav-stacked">
      <li class="active"><a href="#tab1" data-toggle="tab" class="analistic-01">Tab 1</a></li>
      <li class=""><a href="#tab2" data-toggle="tab" class="analistic-02">Tab 2</a></li>
      <li class=""><a href="#tab3" data-toggle="tab" class="analistic-03">Tab 3</a></li>
    </ul>
  </div>
  <div class="tab-content">
    <div class="tab-pane active in" id="tab1">
      <p> hello 1</p>
    </div>

    <div class="tab-pane" id="tab2">
      <p> hello 2</p>
    </div>

    <div class="tab-pane" id="tab3">
      <p>Hello 3</p>
    </div>
  </div> <!--/.tab-content-->
</div><!--/.tab-wrap-->
Run Code Online (Sandbox Code Playgroud)

默认情况下它使tab1处于活动状态,因此在我的情况下可能会根据我的URL链接默认激活第二个选项卡.

假设我将#tab2放在URL中,那么它应该在页面加载时默认使tab2处于活动状态.

Ani*_*war 19

你可以使用像这样的jquery来实现它.您的网址,例如"www.myurl.com/page#tab1";

var url = window.location.href;
Run Code Online (Sandbox Code Playgroud)

从网址链接获取标签以激活.

 var activeTab = url.substring(url.indexOf("#") + 1);
Run Code Online (Sandbox Code Playgroud)

删除旧的活动Tab类

 $(".tab-pane").removeClass("active in");
Run Code Online (Sandbox Code Playgroud)

将活动类添加到新选项卡

$("#" + activeTab).addClass("active in");
Run Code Online (Sandbox Code Playgroud)

或者在获得activeTab后直接打开选项卡.

$('a[href="#'+ activeTab +'"]').tab('show')
Run Code Online (Sandbox Code Playgroud)

  • 或者只是删掉中间人,并使用`document.location.hash`来获取访问过的URL末尾的哈希值 (6认同)

小智 13

  1. 从 URL 获取哈希值并显示活动选项卡
  2. 将当前哈希设置为 URL

您可以使用此代码:

$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav.nav-pills a[href="' + hash + '"]').tab('show'); 
  $('ul.nav.nav-pills a').click(function (e) {
     $(this).tab('show');
     var scrollmem = $('body').scrollTop();
     window.location.hash = this.hash;
  });
});
Run Code Online (Sandbox Code Playgroud)