为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

手掌心 2022-12-22 14:33:57
伙计们,我试图在 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任何帮助,将不胜感激。谢谢
查看完整描述

2 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

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

html {scroll-behavior: smooth;}


查看完整回答
反对 回复 2022-12-22
?
ITMISS

TA贡献1871条经验 获得超8个赞

你可能想尝试这样的事情,


$(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;

}


查看完整回答
反对 回复 2022-12-22
  • 2 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信