首页 > 解决方案 > 从屏幕上的按钮 (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>

我已经构建了屏幕按钮,但不确定如何根据需要向前/向后移动索引。元素“雷达”只是我在显示循环中使用的一系列图像。

标签: htmlarraysfor-loopbuttonindexing

解决方案


要保持轮播并允许按钮将其向前\向后移动,您可以使用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>

推荐阅读