图像按钮开始闪烁

时间:2018-06-21 16:35:49

标签: html image

我有这个html代码:

    <script>
        var image =  document.getElementById("LOC");

        function changeColor()
        {
            if (image.getAttribute('src') == "LOC.gif")
            {
                image.src = "LOC2.gif";
            }
            else
            {
                image.src = "LOC.gif";
            }
        }
    </script>
</body>

<img id ="LOC" src ="LOC.gif" onclick = "changeColor()"/>

我想这样做,如果我单击以显示LOC.gif图像,它开始闪烁,然后再按一次,它将更改为LOC2.gif。然后再次单击->开始闪烁->再次单击->更改回LOC.gif

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试一下

var tId, images = [],
  isBlinking = false;
currImg = 0,

images[0] = new Image(); images[0].src = "https://placehold.it/100x100?text=LOC";
images[1] = new Image(); images[1].src = "https://placehold.it/100x100?text=LOC2";
images[2] = new Image(); images[2].src = "https://placehold.it/100x100?text=BLANK";

window.onload = function() {
  var img = document.getElementById("LOC");

  img.onclick = function() {
    if (isBlinking) {
      clearInterval(tId);
      isBlinking = false;
      currImg = currImg == 0 ? 1 : 0;
      img.src = images[currImg].src;

    } else {
      isBlinking = true;
      tId = setInterval(function() {
        var src = document.getElementById("LOC").src;
        // blink
        document.getElementById("LOC").src = src == images[currImg].src ? images[2].src : images[currImg].src;
      }, 300);
    }

  }
}
Click image it starts blinking then click again, it changes image. Then again click -> starts blinking -> click again -> change back to original
<hr/>

<img id="LOC" src="https://placehold.it/100x100?text=LOC" />