javascript - 我怎样才能重复这个循环的幻灯片,以便在到达最后一个元素时再次播放
问题描述
基本上,我知道必须使用像 count 这样的变量来存储数组中元素的原始数量,但它应该附加到循环的部分尚不清楚。任何帮助都意义重大。谢谢!
let slider = document.getElementById('slider');
const imagesArray = [
'https://images.pexels.com/photos/572897/pexels-photo-572897.jpeg? auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/2832039/pexels-photo-2832039.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'https://images.pexels.com/photos/2574643/pexels-photo-2574643.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940'
]
let count = 0; //I know that we need this, but can't think of attaching it to the array somehow.
imagesArray.forEach((image, i) => {
window.setTimeout(() => {
slider.style.backgroundImage = `url(${image})`;
}, 1000 * i);
});
#slider{
width:auto;
height:300px;
margin:16px;
background-size:cover;
background-repeat:none;
}
<div id="slider"></div>
解决方案
不要在循环中创建images.length
超时,而是定义一个显示“当前”图像并设置超时以显示下一个图像的函数。
然后很容易将其修改为“环绕”到开头:
function showNext(i) {
if (i === imagesArray.length) {
i = 0; // wrap around
}
slider.style.backgroundImage = `url(${imagesArray[i]})`;
setTimeout(() => showNext(i+1), 1000)
}
showNext(0); // start
如果您想从头开始重新启动,您的循环方法将不起作用,因为它明确表示“为数组中的每个元素执行一次”。
推荐阅读
- python - Specifying Schema of CSV in Apache Spark
- logstash - 在 Logstash 过滤器中拥有多个 grok 模式的正确方法是什么?
- magento-1.9 - Magento 1.9 - 在订单历史页面中显示可配置的产品图片
- python - 以两种或多种方式连接到服务,在 Python 中委托方法执行
- android - TranslateAnimation 第一次不起作用
- ruby-on-rails - Rails 没有这样的文件或目录@rb_sysopen。无法从上传目录获取文件内容
- python - 如何使用 Tkinter 在 Python 中将 Enter 键连接到按钮
- mongodb - 地理空间查询不适用于某些位置
- android - 改造 POST 请求 - 解析两个具有相同名称的 JSON 对象
- php - PHP | 如何用'for'读取文件行?