鼠标悬停时如何暂停setInterval?

时间:2019-07-06 14:17:40

标签: javascript jquery html

鼠标悬停时如何暂停setInterval?

$(document).ready(function() {
var MyClass = $(".myclass");
  if (MyClass.hover()) {

  } else {
  setInterval(test, 1000);

  function test() {
    $("#color").click();
  }
  }
});

此代码不起作用!

All code in Fiddle link

1 个答案:

答案 0 :(得分:0)

尝试一下:

$(document).ready(function() {
  var myClass = $(".myclass");

  function test() {
      $("#color").click();
  }
  
  var timerId = setInterval(test, 1000);
  
  myClass.hover(
    function() {
      window.clearInterval(timerId);
    }, function() {
      timerId = setInterval(test, 1000);
    }
  );
  
  
});

document.getElementById('color').onclick = changeColor; 
var currentColor = "red";
function changeColor() { 
  if(currentColor == "red"){ 
     document.body.style.color = "green";
     currentColor = "green";
  } else {
     document.body.style.color = "red";
     currentColor = "red";
  } 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="color">
click
</button>

<div class="myclass">
Mouse Hover
</div>
<div id="myid" style="width:30px;height:30px;">
Change color
</div>