无法使用 Jquery animate 函数实现平滑滚动

伙计们,我试图在 JQuery 的帮助下在我的网页上实现平滑滚动功能。


每当我单击导航项时,页面都应滚动到特定部分。但那并没有发生。


这是我的 index.js 代码


$("#navbar a, .btn").on("click", function (event) {

  if (this.hash != "") {

    event.preventDefault();

    const hash = this.hash;


    $("html", "body").animate(

      {

        scrollTop: $(hash).offset().top - 100,

      },

      800

    );

  }

});

这是网站的链接尝试单击任何导航项并查看。 https://umakanth-pendyala.github.io/Edge-Ledger/


这是我的回购协议的链接 https://github.com/umakanth-pendyala/Edge-Ledger.git


任何帮助,将不胜感激。谢谢


手掌心
浏览 110回答 2
2回答

撒科打诨

让它平稳运行的一种简单方法是将毫秒设置为 0 而不是 800,并将该scroll-behavior: smooth;属性添加到html标记中。html {scroll-behavior: smooth;}

ITMISS

你可能想尝试这样的事情,$(document).ready(function(){  // Add smooth scrolling to required elements, here I've considered all the buttons with   //class name 'button'  $(".button").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  });});或者,为整个文档添加平滑滚动行为。html {  scroll-behavior: smooth;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript