【问题标题】:Smooth scrolling not working jQuery平滑滚动不起作用jQuery
【发布时间】:2026-01-27 20:30:02
【问题描述】:

使用来自 https://css-tricks.com/snippets/jquery/smooth-scrolling/ 的代码以及像我这样的人无法弄清楚为什么它不起作用。

脚本:

$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    || location.hostname == this.hostname) {

    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
         $('html,body').animate({
             scrollTop: target.offset().top
        }, 1000);
        return false;
    }
}
});

网站: www.soelite.net/layout/

有什么想法吗?网站跳转到 div 容器,但没有动画。

【问题讨论】:

  • 在您的问题中也向我们展示您的 HTML,这是让我们为您提供帮助的更好更快的方式
  • 对我来说很好。它到底在哪里不起作用?请提供一个工作流程来重现您的问题。
  • @jahler 似乎无法在 safari 中使用。

标签: javascript jquery html css


【解决方案1】:

看到这个答案:https://*.com/a/2234749/606104

我在 safari 和 chrome (Mac) 中遇到了这个问题,发现 .scrollTop 可以在 $("body") 但不是 $("html, body")

要使其在 Safari 中运行,请将您的脚本更改为:

$('a[href*=#]:not([href=#])').click(function() {
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    || location.hostname == this.hostname) {

    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

    if (target.length) {
      var bodyElement = $("html,body");
      if ($.browser.safari) { 
        bodyElement = $("body")
      }

      bodyElement.animate({
        scrollTop: target.offset().top
      }, 1000);

      return false;
    }
  }
});

【讨论】:

  • 尝试了这个,它在所有浏览器中完全停止工作。