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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7862233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:52:45  来源:igfitidea点击:

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

javascripthtmltabstwitter-bootstrap

提问by mraliks

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 not know how go directly to a specific tab from an external link. For example:

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

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

should go to the Home tab and the Notes tab respectively when clicked on the links from an external page

单击外部页面的链接时,应分别转到“主页”选项卡和“备注”选项卡

回答by dubbe

Here is my solution to the problem, a bit late perhaps. But it could maybe help others:

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

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

回答by flynfish

UPDATE

更新

For Bootstrap 3, change .on('shown', ...)to .on('shown.bs.tab', ....)

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



This is based off of @dubbeanswer 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

这是基于@dubbe答案和这个SO 接受的答案。它处理window.scrollTo(0,0)无法正常工作的问题。问题是,当您替换显示的选项卡上的 url 哈希时,浏览器将滚动到该哈希,因为它是页面上的一个元素。为了解决这个问题,添加一个前缀,这样哈希就不会引用实际的页面元素

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

如果您有带有 id="mytab" 的选项卡窗格,则需要像这样放置链接:

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

回答by Marian Theisen

you could trigger a clickevent on the corresponding tab link:

您可以click在相应的选项卡链接上触发事件:

$(document).ready(function(){

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

});

回答by Demircan Celebi

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

这是 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
    }
})

回答by Peter

While the JavaScript solution provided may work, I went a slightly different way that requires no additional JavaScript, but does require logic in your view. You create a link with a standard URL parameter, like:

虽然提供的 JavaScript 解决方案可能有效,但我采用了一种稍微不同的方式,不需要额外的 JavaScript,但在您的视图中确实需要逻辑。您创建一个带有标准 URL 参数的链接,例如:

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

Then you simply detect the value of activeTab to write 'class="active"' in the appropriate <li>

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

Pseudocode (implement accordingly in your language). Note I've set 'home' tab as a default active if no parameter provided in this example.

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

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

回答by visitsb

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

我不是 if...else 的忠实粉丝;所以我采取了更简单的方法。

$(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
  1. 选择一个默认选项卡(通常是第一个)
  2. 切换到选项卡(如果确实存在这样的元素;让 j​​Query 处理它);如果指定了错误的散列,则不会发生任何事情
  3. [可选] 如果手动选择另一个选项卡,则更新哈希

Doesn't address scrolling to requested hash; but shouldit?

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

回答by Razan Paul

For Bootstrap 3:

对于引导程序 3:

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

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

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

回答by greggdavis

This works in Bootstrap 3 and improves dubbe and flynfish 's 2 top answers by integrating GarciaWebDev 's answer as well (which allows for url parameters after the hash and is straight from Bootstrap authors on the github issue tracker):

这适用于 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);
});

回答by Gavin

Building on Demircan Celebi's solution; I wanted the tab to open when modifying the url and open tab without having to reload the page from the server.

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

回答by Sucrentheitroad

This code selects the right tab depending on the #hash and adds the right #hash when a tab is clicked. (this uses jquery)

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

In Coffeescript :

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

or in JS :

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