gpt4 book ai didi

javascript - 添加滚动速度功能

转载 作者:行者123 更新时间:2023-11-27 23:22:26 25 4
gpt4 key购买 nike

我有以下代码。我如何使用 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>

最佳答案

这是一种方法 - 将要移动的像素数除以移入的时间。使用 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>

关于javascript - 添加滚动速度功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35275302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com