Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 平滑滚动在处理后跳回页面顶部_Jquery_Smooth Scrolling - Fatal编程技术网

Jquery 平滑滚动在处理后跳回页面顶部

Jquery 平滑滚动在处理后跳回页面顶部,jquery,smooth-scrolling,Jquery,Smooth Scrolling,我有一个使用jquery的平滑滚动函数,它可以从页面顶部滚动到从URL散列中拉出来的锚 滚动可以正常工作,但当它完成时,页面将重置为顶部 这是如何实现的: if (hash) { // if hash in the URL $('html, body') .animate({scrollTop:$(window.location.hash) .offset().top - 200 }, 1000); } 什么原因可能导致这种情况?最可能的问题是图

我有一个使用jquery的平滑滚动函数,它可以从页面顶部滚动到从URL散列中拉出来的锚

滚动可以正常工作,但当它完成时,页面将重置为顶部

这是如何实现的:

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

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

什么原因可能导致这种情况?

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

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


请确保在加载图像等后运行此操作,因此将其放入$window.loadfunction{/*您的代码在这里*/};这就解决了问题。谢谢
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); 
  }
});