【问题标题】:href links to Bootstrap nav tabs not activating on same page指向 Bootstrap 导航选项卡的 href 链接未在同一页面上激活
【发布时间】:2013-09-03 03:56:06
【问题描述】:

我已经从这里实现了 psulek 的解决方案:Twitter Bootstrap - Tabs - URL doesn't change 以允许所有站点页面上的右侧导航部分转到带有导航选项卡的页面,并打开选定的选项卡,例如单击下面的区域搜索链接将带您进入 index.html 并选择/打开#region-form

    <p><a href="index.html#airport-form" >Airport Search</a></p>
    <p><a href="index.html#postcode-form">Postcode Search</a></p>
    <p><a href="index.html#region-form">Region Search</a></p>

这很好用,除了 index.html 本身,即带有标签的页面。此页面也有右侧导航部分,其中包含与上述相同的链接。如果 Airport Search 选项卡处于活动状态并且您单击 Region Search 链接,则 URL 将更改为 /index.html#region-form 但 Region 选项卡不会激活。如果我手动刷新/重新加载页面,则会激活“区域”选项卡。

如何让 index.html 上的 rh href 链接自动“工作”并激活选项卡,例如我想我想在单击链接时强制重新加载 index.html 的页面,但不确定最好的方法。

【问题讨论】:

标签: javascript twitter-bootstrap tabs nav


【解决方案1】:

这是一个通用示例,可​​用于 nav-pills 和 nav-tabs 允许任何链接也控制该“页面内”导航的选项卡。

HTML

<a href="#aaa" class="control-tabs">Another Link a</a> 
<a href="#bbb" class="control-tabs">Another Link b</a>
<ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>

JS

        // Javascript to enable link to tab
        var url = document.location.toString();
        console.log('url',url);
        if (url.match('#')) {
            var tid = url.split('#')[1];
            console.log('tid',tid);
            $('.nav a[href$=#'+tid+']').tab('show') ;
            window.scrollTo(0, 0);
        }

        // Change hash for page-reload
        $('.nav a').on('shown.bs.tab', function (e) {
            window.location.hash = e.target.hash;
            window.scrollTo(0, 0);
        })

        // other links to control tabs
        $(".control-tabs").click(function(){
            var url = $(this).attr('href');
            console.log('url',url);
            if (url.match('#')) {
                var tid = url.split('#')[1];
                console.log('tid',tid);
                $('.nav a[href$=#'+tid+']').tab('show') ;
                window.scrollTo(0, 0);
            }
        });

【讨论】:

  • 感谢分享。非常有帮助。现在,我在单页和上面的脚本中使用了 3 组导航选项卡,并且我删除了“window.scrollTo(0, 0);”。我希望内容滚动到顶部。现在我也在使用固定顶部的菜单栏,如何在脚本中添加偏移顶部和平滑动画?
猜你喜欢
  • 2016-02-16
  • 2015-01-08
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2019-11-02
  • 1970-01-01
相关资源
最近更新 更多