如何使用 JavaScript/jQuery 滚动到页面顶部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4210798/
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
How to scroll to top of page with JavaScript/jQuery?
提问by Yarin
Is there a way to control browser scrolling with JavaScript/jQuery?
有没有办法用 JavaScript/jQuery 控制浏览器滚动?
When I scroll my page half way down, then trigger a reload, I want the page to go pack to the top, but instead it tries to find the last scroll position. So I did this:
当我将页面向下滚动一半,然后触发重新加载时,我希望页面打包到顶部,但它会尝试找到最后一个滚动位置。所以我这样做了:
$('document').ready(function() {
$(window).scrollTop(0);
});
But no luck.
但没有运气。
EDIT:
编辑:
So both your answers worked when I call them after the page loads-Thanks. However, if I just do a refresh on the page, looks like the browser calculates and scrolls to its old scroll position AFTER the .ready
event (I tested the body onload() function too).
所以当我在页面加载后给他们打电话时,你的两个答案都有效 - 谢谢。但是,如果我只是在页面上刷新,看起来浏览器会在.ready
事件发生后计算并滚动到旧的滚动位置(我也测试了主体 onload() 函数)。
So the follow up is, is there a way to PREVENT the browser scrolling to its past position, or to re-scroll to the top AFTER it does its thing?
所以后续是,有没有办法阻止浏览器滚动到它过去的位置,或者在它完成它的事情后重新滚动到顶部?
采纳答案by RayLoveless
Wow, I'm 9 years late to this question. Here you go:
哇,我问这个问题晚了 9 年。干得好:
Add this code to your onload.
将此代码添加到您的 onload。
// This prevents the page from scrolling down to where it was previously.
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
// This is needed if the user scrolls down during page load and you want to make sure the page is scrolled to the top once it's fully loaded. This has Cross-browser support.
window.scrollTo(0,0);
history.scrollRestoration Browser support:
history.scrollRestoration 浏览器支持:
Chrome: supported (since 46)
Chrome:支持(自 46 起)
Firefox: supported (since 46)
Firefox:支持(自 46 起)
IE/Edge: not supported(Yet..)
IE/Edge:不支持(但..)
Opera: supported (since 33)
Opera:支持(自 33 起)
Safari: supported
Safari:支持
For IE/Edge if you want to re-scroll to the top AFTER it autoscrolls down then this worked for me:
对于 IE/Edge,如果你想在它自动向下滚动后重新滚动到顶部,那么这对我有用:
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
var isEdge = /Edge/.test(navigator.userAgent);
if(isIE11 || isEdge) {
setTimeout(function(){ window.scrollTo(0, 0); }, 300); // adjust time according to your page. The better solution would be to possibly tie into some event and trigger once the autoscrolling goes to the top.
}
回答by Niet the Dark Absol
Cross-browser, pure JavaScript solution:
跨浏览器的纯 JavaScript 解决方案:
document.body.scrollTop = document.documentElement.scrollTop = 0;
回答by Jacob Relkin
You almostgot it - you need to set the scrollTop
on body
, not window
:
你几乎明白了 - 你需要设置scrollTop
on body
,而不是window
:
$(function() {
$('body').scrollTop(0);
});
EDIT:
编辑:
Maybe you can add a blank anchor to the top of the page:
也许您可以在页面顶部添加一个空白锚点:
$(function() {
$('<a name="top"/>').insertBefore($('body').children().eq(0));
window.location.hash = 'top';
});
回答by Matt
Is there a way to PREVENT the browser scrolling to its past position, or to re-scroll to the top AFTER it does its thing?
有没有办法阻止浏览器滚动到它过去的位置,或者在它完成它的事情后重新滚动到顶部?
The following jquery solution works for me:
以下 jquery 解决方案对我有用:
$(window).unload(function() {
$('body').scrollTop(0);
});
回答by ulfryk
Here's a pure JavaScript animated scroll version for no-jQuery'ers :D
这是一个纯 JavaScript 动画滚动版本,适用于非 jQuery 用户:D
var stepTime = 20;
var docBody = document.body;
var focElem = document.documentElement;
var scrollAnimationStep = function (initPos, stepAmount) {
var newPos = initPos - stepAmount > 0 ? initPos - stepAmount : 0;
docBody.scrollTop = focElem.scrollTop = newPos;
newPos && setTimeout(function () {
scrollAnimationStep(newPos, stepAmount);
}, stepTime);
}
var scrollTopAnimated = function (speed) {
var topOffset = docBody.scrollTop || focElem.scrollTop;
var stepAmount = topOffset;
speed && (stepAmount = (topOffset * stepTime)/speed);
scrollAnimationStep(topOffset, stepAmount);
};
And then:
进而:
<button onclick="scrollTopAnimated(1000)">Scroll Top</button>
回答by Jo E.
UPDATE
更新
Going to top of the page with a scroll effect is a bit more easier in javascript now with:
使用滚动效果转到页面顶部现在在 javascript 中更容易一些:
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
CAUTION
警告
We have been using this in our more recent projects, but I just checked the mozilla doc right now while updating my answer and I believe it has been updated. Right now the method is window.scroll(x-coord, y-coord)
and does not mention or show examples that use the object
parameter where you can set the behavior
to smooth
. I just tried the code and it still works in chrome and firefox and the object parameter is still in the spec.
我们一直在最近的项目中使用它,但我现在只是在更新我的答案时检查了 mozilla 文档,我相信它已经更新。现在,该方法window.scroll(x-coord, y-coord)
没有提及或显示使用object
参数的示例,您可以在其中behavior
将smooth
. 我刚刚尝试了代码,它在 chrome 和 firefox 中仍然有效,并且 object 参数仍在规范中。
So use this with caution or you can use this Polyfill. Aside from scrolling to the top, this polyfill also handles other methods: window.scrollBy
, element.scrollIntoView
, etc.
所以请谨慎使用它,或者你可以使用这个Polyfill。除了滚动到顶部,这也填充工具处理其他方法:window.scrollBy
,element.scrollIntoView
,等。
OLD ANSWER
旧答案
This is our vanilla javascript
implementation. It has a simple easing effect so that the user doesn't get shocked after clicking the To Topbutton.
这是我们的香草javascript
实现。它具有简单的缓动效果,因此用户在单击“顶部”按钮后不会感到震惊。
Its very small and gets even smaller when minified. Devs looking for an alternative to the jquery method but want the same results can try this.
它非常小,缩小后变得更小。正在寻找 jquery 方法的替代方法但希望获得相同结果的开发人员可以试试这个。
JS
JS
document.querySelector("#to-top").addEventListener("click", function(){
var toTopInterval = setInterval(function(){
var supportedScrollTop = document.body.scrollTop > 0 ? document.body : document.documentElement;
if (supportedScrollTop.scrollTop > 0) {
supportedScrollTop.scrollTop = supportedScrollTop.scrollTop - 50;
}
if (supportedScrollTop.scrollTop < 1) {
clearInterval(toTopInterval);
}
}, 10);
},false);
HTML
HTML
<button id="to-top">To Top</button>
Cheers!
干杯!
回答by Chanderkesh Kumar
You can use with jQuery
您可以与 jQuery 一起使用
jQuery(window).load(function(){
jQuery("html,body").animate({scrollTop: 100}, 1000);
});
回答by user113716
This works for me:
这对我有用:
window.onload = function() {
// short timeout
setTimeout(function() {
$(document.body).scrollTop(0);
}, 15);
};
Uses a short setTimeout
inside the onload
to give the browser a chance to do the scroll.
setTimeout
在里面使用 shortonload
使浏览器有机会进行滚动。
回答by Shoaib Quraishi
Use the following function
使用以下功能
window.scrollTo(xpos, ypos)
Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
这里 xpos 是必需的。沿 x 轴(水平)滚动到的坐标,以像素为单位
ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels
ypos 也是必需的。沿 y 轴(垂直)滚动到的坐标,以像素为单位
回答by Ekin Erta?
$(function() {
// the element inside of which we want to scroll
var $elem = $('#content');
// show the buttons
$('#nav_up').fadeIn('slow');
$('#nav_down').fadeIn('slow');
// whenever we scroll fade out both buttons
$(window).bind('scrollstart', function(){
$('#nav_up,#nav_down').stop().animate({'opacity':'0.2'});
});
// ... and whenever we stop scrolling fade in both buttons
$(window).bind('scrollstop', function(){
$('#nav_up,#nav_down').stop().animate({'opacity':'1'});
});
// clicking the "down" button will make the page scroll to the $elem's height
$('#nav_down').click(
function (e) {
$('html, body').animate({scrollTop: $elem.height()}, 800);
}
);
// clicking the "up" button will make the page scroll to the top of the page
$('#nav_up').click(
function (e) {
$('html, body').animate({scrollTop: '0px'}, 800);
}
);
});
Use This
用这个