在mouseout上停止setInterval

时间:2018-09-06 03:36:25

标签: javascript jquery

我试图在悬停效果上创建一个简单的图像旋转器。它可以在鼠标悬停时正常​​工作,但是在使用鼠标移出方法时不起作用。

var imgFlip = $("img").data( "flip" );
var imgOriginal = $("img").data( "original" );
var images = imgFlip.split(/,|, |;|; /);
var index = 0;

function rotateImage()
{
  $('.img-rotator').fadeOut('fast', function() 
  {
    $(this).attr('src', images[index]);

    $(this).fadeIn('fast', function() 
    {
      if (index == images.length-1)
      {
        index = 0;
      }
      else
      {
        index++;
      }
    });
  });
} 

$(document).ready(function()
{
  $('.img-rotator') 
    .mouseover(function () {
      var refreshIntervalId = setInterval (rotateImage, 1000);
    })
    .mouseout(function () {
        $(this).attr('src', imgOriginal);
   })
});

此处是Jsfiddle示例-https://jsfiddle.net/wbz35L68/15/ 谢谢您的任何建议

1 个答案:

答案 0 :(得分:3)

您需要清除setInterval上的mouseout。我还重新编写了一些代码以清理内容并缓存引用。您还应该为此使用mouseentermouseleave

$(document).ready(function(){
  // cache selector
  var rotator = $('.img-rotator'),
      // grab all data
      data = rotator.data(),
      // ref flip
      imgFlip = data.flip,
      // ref original
      imgOriginal = data.original,
      // get image urls
      images = imgFlip.split(/,|, |;|; /),
      // start index
      index = 0,
      // ref interval
      refreshIntervalId = null;

  function rotateImage(){
    rotator.fadeOut('fast', function(){
      $(this)
        .attr('src', images[index])
        .fadeIn('fast', function(){
          var last = index === images.length - 1;
          
          index = last ? 0 : index + 1; 
      });
    });
  } 

  rotator
    .mouseenter(function(){
      refreshIntervalId = setInterval(rotateImage, 1000);
    })
    .mouseleave(function(){
      // clear interval and set null
      clearInterval(refreshIntervalId) && (refreshIntervalId = null); 
      
      $(this).attr('src', imgOriginal);
   })
});
.container {
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col">
      <img class="img-rotator" data-flip="http://www.snorkl.tv/dev/loaderMax/images/bird.png, http://www.snorkl.tv/dev/loaderMax/images/whale.png" data-original="http://www.snorkl.tv/dev/loaderMax/images/crab.png" src="http://www.snorkl.tv/dev/loaderMax/images/crab.png" width="320" height="200"/>
    </div>
  </div>
</div>