【问题标题】:Unable to implement smooth scrolling using Jquery animate function无法使用 Jquery animate 函数实现平滑滚动
【发布时间】:2020-08-05 14:47:46
【问题描述】:

伙计们,我正在尝试借助 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

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

【问题讨论】:

  • 我无法让它滚动,但我认为你需要在你的 scrollTop 值中添加“px”
  • 错字。 $('html', 'body') 应该是 $('html, body'),或者只是 $('html')
  • 是的,这是您在第二条评论中提到的错字,谢谢您的帮助。现在它工作完美

标签: jquery css


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    html {scroll-behavior: smooth;}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      相关资源
      最近更新 更多