锚点过渡与标签引导点击功能冲突

Anchor Transition conflicting with Bootstrap click function for Tabs

本文关键字:冲突 功能 标签      更新时间:2023-09-26

我试图使用一个引导选项卡单击功能,但我也有麻烦使用动画的锚标签我从stackoverflow得到。似乎点击功能弄乱了标签的点击功能有办法解决这个问题吗?

<div id="tab1">
    <ul class="tab1-titles">
        <li class="active">
            <a href="#1a" data-toggle="tab">Tab1</a>
        </li>
        <li>
            <a href="#2a" data-toggle="tab">Tab2</a>
        </li>
    </ul>
    <div class="tab-content">
        <div class="tab-pane active" id="1a">
            <ul>
               <li>list-item-1</li>
               <li>list-item-2</li>
            </ul>
        </div>
        <div class="tab-pane active" id="2a">
            <ul>
               <li>list-item-1</li>
               <li>list-item-2</li>
            </ul>
        </div>
    </div>
</div>
Javascript

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
  if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
}
});
});

不添加新的click事件处理程序,只需使用内置的选项卡更改事件,如下所示

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    var hash = $(e.target).attr("href");
    //your code goes here
    if (location.pathname.replace(/^'//, '') == this.pathname.replace(/^'//, '') && location.hostname == this.hostname) {
        var target = $(hash);
        target = target.length ? target : $('[name=' + hash.slice(1) + ']');
        if (target.length) {
            $('html,body').animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    }
});

我有一个同事帮我看了一下,他建议在这个脚本中添加一个类到锚标记。所以我照做了,而且效果很好!我只需要更直接地调用这个函数就可以了。他甚至添加了一个偏移滚动顶,以防你有一个固定的标题到方程式。

$('a[href^="#"].anchortargets:not([href="#"])').click(function() {
        if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: parseInt(target.offset().top) - 140 + 'px'
            }, 500);
            return false;
          }
        }
      });