添加滚动速度功能

时间:2016-02-08 17:09:43

标签: javascript

我有以下代码。 我如何使用setInterval或setTimeout使跳跃从0px到500px发生在3000ms?

<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 5000px;
}
</style>
</head>
<body>

<p>Click the button to scroll the document window to 500 pixels horizontally.</p>

<button onclick="scrollWin()">Click me to scroll horizontally!</button><br>    <br>

<script>
function scrollWin() {
window.scrollTo(500, 0);
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

这是一种方法 - 将要移动的像素数除以要移入的时间。使用setInterval在一定的固定时间内移动该像素数inervalTime。然后,取消滚动位置到达目标时的间隔。

function scrollWin(target, time) {
  var currentPosition = window.pageXOffset || document.documentElement.scrollLeft;
  var scrollInterval = target / time;
  var intervalTime = 10;
  var intervalFunction;
  intervalFunction = setInterval(function() {
    currentPosition = currentPosition + scrollInterval * intervalTime;
    window.scrollTo(currentPosition, 0);
    if (currentPosition >= target) {
      window.clearInterval(intervalFunction);
    }
  }, intervalTime)
}
body {
  width: 5000px;
}
<p>Click the button to scroll the document window to 500 pixels horizontally.</p>

<button onclick="scrollWin(500, 3000)">Click me to scroll horizontally!</button>