【问题标题】:Smooth scroll jumps back to top of page after processing处理后平滑滚动跳回页面顶部
【发布时间】:2017-10-25 21:23:19
【问题描述】:

我有一个使用 jquery 的函数,该函数具有从页面顶部滚动到从 URL 哈希中拉出的锚点的平滑滚动。

滚动工作正常,但完成后,页面会重置到顶部。

这是如何实现的:

 if (hash) { // if hash in the URL

    $('html, body')
      .animate({scrollTop:$(window.location.hash) 
        .offset().top - 200 }, 1000); 
  }

这可能是什么原因造成的?

【问题讨论】:

  • 确保在图片等加载后运行它,所以把它放在$(window).load(function(){/*your code here*/});
  • 修复了它。谢谢!

标签: jquery smooth-scrolling


【解决方案1】:

最可能的问题是图像和其他内容尚未加载,因此页面尚未收到其最终尺寸。这样,初始滚动条在加载后会指向错误的位置。

这种情况的一个好方法是在内容加载后执行滚动,因此您必须将代码包装在 $(window).load 方法中。

var hash = window.location.hash;
$(window).load(function(){
  if (hash) { // if hash in the URL

    $('html, body')
      .animate({scrollTop:$(window.location.hash) 
        .offset().top - 200 }, 1000); 
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多