自动按钮循环

时间:2017-03-22 17:40:01

标签: javascript html

我能够让按钮处于点击状态并延迟使其成为半自动,但我需要它在一次点击后不要暂停。这是我到目前为止所做的。

<!DOCTYPE html> 
<html> 
<body>
  <h1>JavaScript</h1>  
  <img id="light" src="./assets/red.jpg">
  <button onClick="changeLights(changelights, 1000)">Change Lights</button>
  <button onClick="clearInterval(changeLights)">Stop Lights!</button>
  <script> 
    var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
    var index = 0;
    function changeLights() {
      index = index + 1;
      if (index == list.length) 
        index = 0;
      var image = document.getElementById('light');
      image.src = list[index]; 
    } 
    setInterval(nxt,200);

  </script>
</body> 
</html>

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望用户能够单击按钮开始循环浏览图像,并通过单击其他按钮来停止它。以下是基于您的代码执行此操作的代码。我已经为2张图片展示了它,但它也适用于更长的列表......

&#13;
&#13;
var keepgoing = false;
var list = [
  "https://s22.postimg.org/84255zdkt/bulboff.jpg",
  "https://s22.postimg.org/5b8xlyd8d/bulbon.jpg"
];
var index = 0;
var image = document.getElementById('light');

function startLights() {
  if (keepgoing) return;
  keepgoing = true;
  changeLights();
}

function changeLights() {
  if (keepgoing) {
    setTimeout(changeLights, 500);
    index = (index + 1) % list.length;
    image.src = list[index];
  }
}
&#13;
<div>
  <button onClick="startLights();">Change Lights</button>
  <button onClick="keepgoing = false;">Stop Lights!</button>
</div>
<img id="light" style="width:100px;" src="https://s22.postimg.org/84255zdkt/bulboff.jpg">
&#13;
&#13;
&#13;