我有一个问题,我想通过调用window.scrollTo()将页面渲染后滚动到特定元素。但是不起作用。有什么限制吗?
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++;
}
}
最佳答案
这行:
setTimeout(window.scrollTo(0,leapY), timer * speed);
立即调用
window.scrollTo
并将其返回值传递给setTimeout
,就像foo(bar())
立即调用bar
并将其返回值传递给foo
一样。您需要传递一个函数:
setTimeout(function() { window.scrollTo(0,leapY); }, timer * speed);
但这还不够,因为该函数将在运行时查看
leapY
值,而不是在定义时查看它,因此它们最终都将使用leapY
的最后一个值。因此,您需要一个构建器函数:setTimeout(buildScroller(leapY), timer * speed);
function buildScroller(y) {
return function() { window.scrollTo(0,y); };
}
在循环中,我们调用生成器,传入
leapY
作为y
参数,它返回一个封闭该参数(而不是leapY
)的函数。该参数不会改变,因此它构建的函数使用正确的值。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>