如何将平滑滚动添加到Bootstrap's的滚动间谍功能

How to add smooth scrolling to Bootstrap's scroll spy function

本文关键字:滚动 功能 间谍 Bootstrap 平滑 添加      更新时间:2023-09-26

我已经尝试为我的网站添加平滑滚动功能一段时间了,但似乎无法实现。

以下是与导航相关的HTML代码:

<div id="nav-wrapper">
<div id="nav" class="navbar navbar-inverse affix-top" data-spy="affix" data-offset-top="675">
  <div class="navbar-inner" data-spy="affix-top">
    <div class="container">
      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </a>
      <!-- Everything you want hidden at 940px or less, place within here -->
      <div class="nav-collapse collapse">
        <ul class="nav">
            <li><a href="#home">Home</a></li>
            <li><a href="#service-top">Services</a></li>
            <li><a href="#contact-arrow">Contact</a></li>
        </ul><!--/.nav-->
      </div><!--/.nav-collapse collapse pull-right-->
    </div><!--/.container-->
  </div><!--/.navbar-inner-->
</div><!--/#nav /.navbar navbar-inverse-->
</div><!--/#nav-wrapper-->

这是我添加的JS代码:

<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script>
    $(document).ready(function(e) {
        $('#nav').scrollSpy()
        $('#nav ul li a').bind('click', function(e) {
            e.preventDefault();
            target = this.hash;
            console.log(target);
            $.scrollTo(target, 1000);
        });
    });
</script>

值得一提的是,这里是我收到的关于我迄今为止所做的事情的信息,这是我的网站的当前形式。如果你能帮我,我会给你烤一个馅饼或饼干什么的。谢谢

你真的需要那个插件吗?您只需设置scrollTop属性的动画:

$("#nav ul li a[href^='#']").on('click', function(e) {
   // prevent default anchor click behavior
   e.preventDefault();
   // store hash
   var hash = this.hash;
   // animate
   $('html, body').animate({
       scrollTop: $(hash).offset().top
     }, 300, function(){
       // when done, add hash to url
       // (default click behaviour)
       window.location.hash = hash;
     });
});

小提琴

如果你有一个固定的导航栏,你需要这样的东西。

从上面最好的答案和评论中。。。

$(".bs-js-navbar-scrollspy li a[href^='#']").on('click', function(event) {
  var target = this.hash;
  event.preventDefault();
  var navOffset = $('#navbar').height();
  return $('html, body').animate({
    scrollTop: $(this.hash).offset().top - navOffset
  }, 300, function() {
    return window.history.pushState(null, null, target);
  });
});

首先,为了防止出现"未定义"错误,在调用preventDefault()之前,将哈希存储到变量target中,然后引用存储的值,如pumpdupa所述。

接下来。不能使用window.location.hash = target,因为它同时设置url和位置,而不是单独设置。您最终会在元素的开头有一个位置,该位置的id与href。。。但被固定的顶部导航栏覆盖。

为了绕过这一点,您将scrollTop值设置为目标的垂直滚动位置值减去固定导航条的高度。直接针对该值可以保持平滑的滚动,而不是在之后添加调整,并使其看起来不专业。

你会注意到网址没有改变。要设置此项,请改用return window.history.pushState(null, null, target);,手动将url添加到历史堆栈中。

完成!

其他注意事项:

1) 使用.on方法是最新的(截至2015年1月)jquery方法,它比.bind.live,甚至.click更好,原因我将留给您来了解。

2) navOffset值可以在函数内部,也可以在函数外部,但您可能希望它在函数之外,因为您很可能会为其他函数/DOM操作引用该垂直空间。但我把它放在里面,使它整齐地成为一个功能。

$("#YOUR-BUTTON").on('click', function(e) {
   e.preventDefault();
   $('html, body').animate({
        scrollTop: $("#YOUR-TARGET").offset().top
     }, 300);
});
// styles.css
html {
    scroll-behavior: smooth
}

来源:https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

如果你下载了jquery轻松插件(检查一下),那么你只需要将其添加到你的main.js文件中:

$('a.smooth-scroll').on('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top + 20
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
});

也不要忘记将平滑滚动类添加到您的a标签中,如下所示:

 <li><a href="#about" class="smooth-scroll">About Us</a></li>

我把它组合在一起,这就是结果-

$(document).ready(function() {
     $("#toTop").hide();
            // fade in & out
       $(window).scroll(function () {
                    if ($(this).scrollTop() > 400) {
                        $('#toTop').fadeIn();
                    } else {
                        $('#toTop').fadeOut();
                    }
                });     
  $('a[href*=#]').each(function() {
    if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'')
    && location.hostname == this.hostname
    && this.hash.replace(/#/,'') ) {
      var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
      var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
       if ($target) {
         var targetOffset = $target.offset().top;
         $(this).click(function() {
           $('html, body').animate({scrollTop: targetOffset}, 400);
           return false;
         });
      }
    }
  });
});

我测试过了,效果很好。希望这能帮助到某人:)

onetrickpony发布的内容可以,但如果您想要一个更通用的解决方案,您可以使用下面的代码。

不必只选择锚点的id,您可以使其更标准,就像只选择<a>-Tag的属性name一样。这将避免您编写额外的id标记。只需将smoothwoll类添加到导航栏元素中即可。

发生了什么变化

1) $('#nav ul li a[href^="#"]')$('#nav.smoothscroll ul li a[href^="#"]')

2) $(this.hash)$('a[name="' + this.hash.replace('#', '') + '"]')

最终代码

/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {
  // prevent default anchor click behavior
  e.preventDefault();
  // store hash
  var hash = this.hash;
  // animate
  $('html, body').animate({
    scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
  }, 300, function(){
    // when done, add hash to url
    // (default click behaviour)
    window.location.hash = hash;
  });
});

使用此代码,id将不会出现在链接上

    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            document.querySelector(this.getAttribute('href')).scrollIntoView({
                behavior: 'smooth'
            });
        });
    });