javascript - 如何使图像在鼠标悬停时多次更改

标签 javascript html setinterval onmouseover

我试图多次更改图像,因此我使用了 setInterval 但它不会停止

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
  </head>
  <body>
    <a href="https://www.google.com" target="_blank">
      <img onmouseover="setInterval(mouseOver,500)" onmouseout="mouseOut()" id="a" src="1.jpg" style="height: 45vh; width: 23vw;">
    </a>
    <script>
      function mouseOver()
      {
        element=document.getElementById("a")
        if (element.src.match("pic_bulboff.jpg"))
        {
          document.getElementById("a").src="8.jpg";
        }
        else if (element.src.match("8.jpg"))
        {
          document.getElementById("a").src="6.jpg";
        }
        else
        {
          document.getElementById("a").src="1.jpg";
        }
      }
      function mouseOut()
      {
        document.getElementById("a").src="1.jpg";
      }
    </script>
  </body>
</html>

最佳答案

使用clearInterval并跟踪初始间隔:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Untitled Document</title>
</head>

<body>
  <a href="https://www.google.com" target="_blank">
    <img onmouseover="init()" onmouseout="mouseOut()" id="a" src="http://placecage.com/400/400" style="height: 45vh; width: 23vw;">
  </a>
  <script>
    var interval;

    function init() {
      interval = setInterval(mouseOver, 500)
    }

    function mouseOver() {
      element = document.getElementById("a")
      if (element.src.match("400/400")) {
        document.getElementById("a").src = "http://placecage.com/300/300";
      } else if (element.src.match("300/300")) {
        document.getElementById("a").src = "http://placecage.com/200/200";
      } else {
        document.getElementById("a").src = "http://placecage.com/500/500";
      }
    }

    function mouseOut() {
      document.getElementById("a").src = "http://placecage.com/400/400";
      clearInterval(interval)
    }
  </script>
</body>

</html>

关于javascript - 如何使图像在鼠标悬停时多次更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41444584/

相关文章:

javascript - 在 JavaScript 和 ActionScript 之间共享数组引用

javascript - 将函数传递给 d3 的 .data()

javascript - Grunt - 将多个文件缩小/处理为一个

html - 水平居中 block /div 并允许它们内联堆叠

javascript - 从 CSS 类中 trim 第一个和最后一个字符

javascript - setInterval 仅在对象方法上运行一次

javascript - Meteor 中的复合集合

javascript - 在 keydown 上使用 javascript 更改样式/类

php - SetInterval() 泄漏内存,导致加载图像时出现问题

Javascript setInterval 随机停止