我以为这会很容易,但是我被卡住了。
我的代码正在执行并且忽略了setTimeout。
我得到了元素的滚动宽度,然后说,当i小于宽度(flavoursScrollWidth)时,每秒水平滚动1px。
但这不是正在发生的事情,它几乎立即执行每个像素移动。
我还尝试将代码从load事件中取出,并将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++;
}
})Run Code Online (Sandbox Code Playgroud)
.container {
width:300px;
overflow-x:scroll;
white-space: nowrap;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
我建议使用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);
})Run Code Online (Sandbox Code Playgroud)
.container {
width:300px;
overflow-x:scroll;
white-space: nowrap;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2453 次 |
| 最近记录: |