我认为这很容易,但我被困住了。
我的代码正在执行并忽略setTimeout。
我得到了我的元素的滚动宽度,然后说i
小于宽度(flavoursScrollWidth
)时,每隔一秒移动水平滚动1px。
这不是正在发生的事情,它只是几乎立即执行每个像素运动。
我还尝试从load事件中取出代码并从while循环中取出setTimeout。然后创建一个包含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>
答案 0 :(得分:5)
我建议使用setInterval
而不是setTimeout
,只检查容器是否滚动到最后。我还发现,如果你滚动得更快,就像每15毫秒一样,你会获得更流畅的用户体验。
const flavoursContainer = document.getElementById("flavoursContainer")
const flavoursScrollWidth = flavoursContainer.scrollWidth
const flavoursContainer2 = document.getElementById("flavoursContainer2")
const flavoursScrollWidth2 = 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;
}
<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>