Javascript ScrollTo不适用于页面加载

时间:2013-07-04 07:16:25

标签: javascript

我有一个问题,我想通过调用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++;
        }            
    }

1 个答案:

答案 0 :(得分:3)

这一行:

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>