Javascript 使用 jQuery 加载页面时自动滚动顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12047323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto scroll top when page loaded using jQuery
提问by Hei
I am trying to use jQuery to scroll the page automatically back to the top when the page is loaded. Here is my code:
我正在尝试使用 jQuery 在页面加载时自动将页面滚动回顶部。这是我的代码:
<script type="text/javascript">
$(document).ready(function () {
$(window).scrollTop(0);
return false;
});
</script>
However, the code does not work.
I have also tried to replace $(window)
to $('html, body')
,
sadly it still does not work.
但是,代码不起作用。我也尝试替换$(window)
为$('html, body')
,遗憾的是它仍然不起作用。
So could anyone advice on this? Thanks a lot!
那么有人可以就此提出建议吗?非常感谢!
回答by fonZ
Try this
尝试这个
<script type="text/javascript">
$(document).ready(function () {
window.scrollTo(0,0);
});
</script>
The parameters 0,0 are the x and y co?rdinates.
参数 0,0 是 x 和 y 坐标。
I hope it helps.
我希望它有帮助。
回答by taylorpoe
The above solutions didn't work for me in Chrome. This is what I had the most success with:
上述解决方案在 Chrome 中对我不起作用。这是我最成功的地方:
$(window).on('beforeunload', function() {
$('body').fadeOut(225);
});
回答by Udo E.
This is jQuery safe:
这是 jQuery 安全的:
< script type="text/javascript">
$(window).scrollTop(0);
</script>
回答by Attilio
Is easier and more reliable if you use this solution:
如果您使用此解决方案,则更容易、更可靠:
<script type="text/javascript">
$('html,body').animate({scrollTop:0},800);
</script>
In fact some browsers will respond to 'html'
and some to 'body'
.
事实上,有些浏览器会响应'html'
,有些会响应'body'
.
PS. "800" is the duration of the animation.
附注。“800”是动画的持续时间。