autoScroll2() { const scrollContainer = this.$refs.scrollContainer2; const scrollContent = this.$refs.scrollContent2; const scrollWidth = scrollContent.scrollWidth; const containerWidth = scrollContainer.offsetWidth; let scrollLeft = 0; let requestId = null; // 用于存储requestAnimationFrame返回的id const scroll = () => { if (scrollLeft < scrollWidth - containerWidth) { scrollLeft += 1; } else { scrollLeft = 0 } scrollContainer.scrollLeft = scrollLeft; requestId = requestAnimationFrame(scroll); } // 先清除之前创建的scroll函数 cancelAnimationFrame(requestId); // 再创建新的scroll函数 requestId = requestAnimationFrame(scroll); } 这段代码我不想要scrollLeft等于0 我想要它接着最后一个一直滚动下去
时间: 2024-02-10 08:10:50 浏览: 33
如果你想让它接着最后一个一直滚动下去,可以将 `scrollLeft = 0` 这一行代码修改为 `scrollLeft = scrollWidth - containerWidth`,这样当 `scrollLeft` 的值超过了 `scrollWidth - containerWidth` 时,就会回到滚动内容的末尾,接着继续滚动。修改后的代码如下:
```
autoScroll2() {
const scrollContainer = this.$refs.scrollContainer2;
const scrollContent = this.$refs.scrollContent2;
const scrollWidth = scrollContent.scrollWidth;
const containerWidth = scrollContainer.offsetWidth;
let scrollLeft = scrollWidth - containerWidth;
let requestId = null; // 用于存储requestAnimationFrame返回的id
const scroll = () => {
if (scrollLeft < scrollWidth - containerWidth) {
scrollLeft += 1;
} else {
scrollLeft = scrollWidth - containerWidth;
}
scrollContainer.scrollLeft = scrollLeft;
requestId = requestAnimationFrame(scroll);
}
// 先清除之前创建的scroll函数
cancelAnimationFrame(requestId);
// 再创建新的scroll函数
requestId = requestAnimationFrame(scroll);
}
```
这样修改后,当滚动到内容的末尾时,会自动回到最后一个元素,接着继续滚动。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)