我认为这会相当容易,但我被困住了。
我的代码正在执行并忽略了 setTimeout。
我正在获取元素的滚动宽度,然后说当 i
小于宽度 (flavoursScrollWidth
) 时,每秒将水平滚动条移动 1px。
虽然实际情况并非如此,它只是几乎立即执行每个像素移动。
我还尝试将代码从加载事件中取出,并将 setTimeout 从 while 循环中取出。然后创建一个包含 while 循环的函数,并在 setInterval 中调用该函数。没有帮助。
const flavoursContainer = document.getElementById("flavoursContainer")
const flavoursScrollWidth = flavoursContainer.scrollWidth
window.addEventListener("load", () => {
let i = 0
while (i < flavoursScrollWidth) {
setTimeout(flavoursContainer.scrollTo(i, 0), 1000)
console.log(i)
i++;
}
})
.container {
width:300px;
overflow-x:scroll;
white-space: nowrap;
}
<div class="container" id="flavoursContainer">
This is a really long sentence to demo my code, it's just going on and on. Still going. I should have used some default placeholder text but I've started now so I'll keep going.
</div>
最佳答案
我建议使用 setInterval
而不是 setTimeout
并且只检查容器是否滚动到末尾。我还发现,如果滚动速度更快,比如每 15 毫秒滚动一次,您将获得更流畅的用户体验。
const flavoursContainer = document.getElementById('flavoursContainer');
const flavoursScrollWidth = flavoursContainer.scrollWidth;
window.addEventListener('load', () => {
self.setInterval(() => {
if (flavoursContainer.scrollLeft !== flavoursScrollWidth) {
flavoursContainer.scrollTo(flavoursContainer.scrollLeft + 1, 0);
}
}, 15);
});
.container {
width: 300px;
overflow-x: scroll;
white-space: nowrap;
background-color: #fff;
}
<div class="container" id="flavoursContainer">
This is a really long sentence to demo my code, it's just going on and on. Still going. I should have used some default placeholder text but I've started now so I'll keep going.
</div>
关于javascript - 自动滚动水平 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968622/