我的HTML文档中有一组div,并使用jQuery每隔15000ms一次显示它们。我还想在某些div中包含一些链接,因此我想在悬停时暂停或延迟div。这是我的脚本代码。有人可以告诉我如何在悬停时暂停吗?

            <script>
var ct = 0;

function showElem2() {
  var length = $('.t1').length;
  $('.t1').hide();
  $('.info span').text(ct);
  $('.t1').eq(ct).fadeIn(900);
  (ct >= (length-1)) ? ct = 0: ct++;
  setTimeout(showElem2, 1600);
}

$(document).ready(function(){
showElem2();

});

    </script>

最佳答案

您可以清除鼠标悬停时的超时,然后在鼠标悬停时再次启动。我更新了您的代码:

var ct = 0;
var myTimeout;

function showElem2() {
  var length = $('.t1').length;
  $('.t1').hide();
  $('.info span').text(ct);
  $('.t1').eq(ct).fadeIn(900);
  (ct >= (length-1)) ? ct = 0: ct++;
  myTimeout = setTimeout(showElem2, 1600);
}

$(document).ready(function(){
  showElem2();
  // $('div') is the container you want to attach the mouseover/mouseout event to.
  $('div').hover(function() {
    // mouseover
    clearTimeout(myTimeout); // cancels the timeout
  }, function() {
    // mouseout
    myTimeout = setTimeout(showElem2, 1600); // starts it again (or technically a new timeout)
  });
});


可能不是最佳的代码解决方案,但是这里的关键是clearTimeout(),让您取消使用setTimeout()设置的超时。

09-25 21:32