简体   繁体   English

使用scrollspy在BS4固定导航栏上平滑滚动

[英]Smooth scrolling on BS4 fixed navbar with scrollspy

WARNING: I'm new to JavaScript. 警告:我是JavaScript新手。

I am developing a site for a family member and I've stumbled upon a problem. 我正在为一个家庭成员开发一个站点,但偶然发现了一个问题。 I am using Bootstrap 4 for the site, and therefor their navbar framework. 我正在为该站点使用Bootstrap 4,因此使用了它们的导航栏框架。 The navbar is fixed to the top, and uses ScrollSpy to highlight the active section. 导航栏固定在顶部,并使用ScrollSpy突出显示活动部分。

I am using this code from W3 to have my Nav links slowly scroll down the page to a section. 我正在使用W3中的这段代码来使我的Nav链接缓慢向下滚动页面至某个部分。

    $(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

No luck. 没运气。 My nav links nolonger work, and I get these nasty console errors 我的导航链接不再起作用,并且出现这些讨厌的控制台错误

master.js:15 Uncaught TypeError: $(...).animate is not a function
    at HTMLAnchorElement.<anonymous> (master.js:15)
    at HTMLAnchorElement.dispatch (jquery-3.2.1.slim.min.js:3)
    at HTMLAnchorElement.q.handle (jquery-3.2.1.slim.min.js:3)

I know what you're thinking, master.js is sourced before jQuery. 我知道您在想什么,master.js是在jQuery之前提供的。 Nope! 不!

I would appreciate any help I can get on this. 我将不胜感激。

See the answer here: jquery : $().animate() is not a function 在这里查看答案: jquery:$()。animate()不是函数

You appear to be using the slim build of jQuery 3.2.1, which doesn't include most of the library. 您似乎正在使用jQuery 3.2.1的苗条版本,该版本不包含大多数库。 Instead, you should be using the full version. 相反,您应该使用完整版本。

https://code.jquery.com/jquery-3.2.1.js https://code.jquery.com/jquery-3.2.1.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM