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

问题描述 投票:6回答:4

我有引导标签,我想在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-->

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

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

jquery twitter-bootstrap tabs
4个回答
16
投票

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

var url = window.location.href;

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

 var activeTab = url.substring(url.indexOf("#") + 1);

删除旧的活动Tab类

 $(".tab-pane").removeClass("active in");

将活动类添加到新选项卡

$("#" + activeTab).addClass("active in");

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

$('a[href="#'+ activeTab +'"]').tab('show')

3
投票

您可以使用此代码:

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

1
投票

根据您设置JS的方式,您应该能够这样做:

www.myurl.com/page#tab1

www.myurl.com/page#tab2

www.myurl.com/page#tab3

其中#tab1#tab2#tab3等于标签的id

编辑

见这里:Twitter Bootstrap - Tabs - URL doesn't change


1
投票

您可以向<ul class="nav nav-tabs nav-stacked" id="myTab">添加ID,然后使用以下javascript代码:

$(document).ready(() => {
  let url = location.href.replace(/\/$/, "");

  if (location.hash) {
    const hash = url.split("#");
    $('#myTab a[href="#'+hash[1]+'"]').tab("show");
    url = location.href.replace(/\/#/, "#");
    history.replaceState(null, null, url);
    setTimeout(() => {
      $(window).scrollTop(0);
    }, 400);
  } 

  $('a[data-toggle="tab"]').on("click", function() {
    let newUrl;
    const hash = $(this).attr("href");
    if(hash == "#home") {
      newUrl = url.split("#")[0];
    } else {`enter code here`
      newUrl = url.split("#")[0] + hash;
    }
    newUrl += "/";
    history.replaceState(null, null, newUrl);
  });
});

有关详细信息follow this link

© www.soinside.com 2019 - 2024. All rights reserved.