html - 从屏幕上的按钮 (html) 迭代数组
问题描述
我正在尝试使用屏幕上的按钮来移动一个向前/向后显示图像的数组。但是,我希望轮播功能保持完整(因此,如果我单击它会重新启动 8 秒周期,如果我什么都不做,它会继续保持原样)。
<script>
var myIndex = 0;
carousel();
function carousel()
{
var i;
var x = document.getElementsByClassName("radar");
for (i = 0; i < x.length; i++)
{
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 8000); // number of seconds
}
</script>
我已经构建了屏幕按钮,但不确定如何根据需要向前/向后移动索引。元素“雷达”只是我在显示循环中使用的一系列图像。
解决方案
要保持轮播并允许按钮将其向前\向后移动,您可以使用clearTimeout函数清除当前回调,然后将其重置。
当按钮用于向前移动轮播时,传入一个标志以重置超时。
试试这个代码:
<script>
var myIndex = 0;
var timeout = null;
carousel();
function carousel(dir) // dir is null if timeout
{
var i;
var x = document.getElementsByClassName("radar");
for (i = 0; i < x.length; i++)
{
x[i].style.display = "none";
}
myIndex+= dir? dir : 1; //if dir is null, no button click, move carousel forward
if (myIndex > x.length) {myIndex = 1}
if (myIndex < 0) {myIndex = x.length}
x[myIndex-1].style.display = "block";
if (dir) { clearTimeout(timeout); } // button click, clear existing timeout
timeout = setTimeout(carousel, 8000); // number of seconds
}
</script>
<body>
<button class="button button1" onclick="carousel(1)" >Next</button>
<button class="button button1" onclick="carousel(-1)">Previous</button>
</body>
推荐阅读
- python - 使用 netCDF4 从 NOAA 读取 grib2 数据
- data-binding - 在 Alpine.js 中将类绑定到 $el.value
- r - 在美国地图下方移动阿拉斯加和夏威夷
- python - 在 Python 列表中,为什么我附加的值与我附加的值不同?
- reactjs - 无法对 Firestore 集合使用 onSnapshot 方法
- python-3.x - 优化深度优先搜索python
- sql - SQL - 按日期分组防止重复
- csv - 行:-1,列:-1 System.StringException:无效 id:'1294888839' Apex
- c++ - 如何在 C++ 中将 2D char 数组转换为 1D char 数组
- c# - 改装说它找不到身份验证方法但它大摇大摆地工作