[英]Javascript ScrollTo does not work on page load
I have a issue, I want to scroll the page to a particular element once the page renders by calling window.scrollTo(). 我有一个问题,我想通过调用window.scrollTo()将页面呈现后滚动到特定元素。 But doesn't work. 但是不起作用。 Any limitations? 有什么限制吗?
var step = Math.round(distance / 25); // distance is Stop-start
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for (var i = startY; i < stopY; i += step) {
setTimeout(window.scrollTo(0,leapY), timer * speed);
leapY += step;
if (leapY > stopY)
leapY = stopY;
timer++;
}
}
This line: 这行:
setTimeout(window.scrollTo(0,leapY), timer * speed);
calls window.scrollTo
immediately and passes its return value into setTimeout
, just like foo(bar())
calls bar
immediately and passes its return value into foo
. 立即调用window.scrollTo
并将其返回值传递给setTimeout
,就像foo(bar())
立即调用bar
并将其返回值传递给foo
。
You need to pass in a function: 您需要传递一个函数:
setTimeout(function() { window.scrollTo(0,leapY); }, timer * speed);
But that alone isn't enough, because the function will look at the leapY
value as it is when it runs , not when it's defined, and so they'll all end up using the last value of leapY
. 但是,仅此还不够,因为该函数将在运行时 (而不是在定义时)看待leapY
值,因此它们最终都将使用最后一个leapY
值。 So you want a builder function: 因此,您需要一个构建器函数:
setTimeout(buildScroller(leapY), timer * speed);
function buildScroller(y) {
return function() { window.scrollTo(0,y); };
}
In the loop, we call the builder passing in leapY
as the y
argument, and it returns a function closing over the argument (rather than leapY
). 在循环中,我们所说的建设者经过leapY
为y
参数,并可以通过参数(而不是返回函数结束leapY
)。 That argument doesn't change, so the function it builds uses the right value. 该参数不会改变,因此它构建的函数使用正确的值。
Live Example | 现场示例 | Live Source 现场直播
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Scrolling On Load In Loop</title>
<style>
div {
height: 200px;
}
</style>
</head>
<body>
<div>Scrolls to each of the first four followingdivs at intervals of one second</div>
<div>0x100</div>
<div>0x200</div>
<div>0x300</div>
<div>0x400</div>
<div>0x500</div>
<div>0x600</div>
<div>0x700</div>
<div>0x800</div>
<div>0x900</div>
<div>0x1000</div>
<div>0x1100</div>
<div>0x1200</div>
<div>0x1300</div>
<div>0x1400</div>
<script>
(function() {
var leapY;
for (leapY = 1; leapY <= 4; ++leapY) {
setTimeout(buildScroller(leapY * 200), leapY * 1000);
}
function buildScroller(y) {
return function() { window.scrollTo(0,y); };
}
})();
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.