如何使用JavaScript滚动到页面顶部

时间:2015-09-18 16:01:51

标签: javascript jquery scroll

如何在页面完全加载后使用JavaScript滚动到页面顶部。

3 个答案:

答案 0 :(得分:0)

尝试:

document.body.scrollTop = document.documentElement.scrollTop = 0;

答案 1 :(得分:0)

使用window.scrollTo(x, y) xy为水平和垂直偏移(以像素为单位)。

答案 2 :(得分:0)

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);
};

然后:

<button onclick="scrollTopAnimated(1000)">Scroll Top</button>