如何暂停悬停在div上并继续使用mouseout?

时间:2015-03-31 19:59:10

标签: javascript jquery

我的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>

2 个答案:

答案 0 :(得分:1)

您可以清除鼠标悬停时的超时,并在mouseout上再次启动它。我更新了你的代码:

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()设置的超时设置。

答案 1 :(得分:1)

我相信您可以将Timeout绑定到变量,这样您就可以在悬停时取消它,然后只需在鼠标输出时重新加载该功能。这还没有经过测试,但我认为这应该有效: :`

            <script>
var ct = 0; 
var timeoutvariable;
function showElem2() {
  var length = $('.t1').length;
  $('.t1').hide();
  $('.info span').text(ct);
  $('.t1').eq(ct).fadeIn(900);

$('.t1').eq(ct).hover(function(){ //on mouse enter
clearTimeout(timeoutvariable);
}, 
function(){ //on mouse leave 
showElem2(); 
});

  (ct >= (length-1)) ? ct = 0: ct++;   
 timeoutvariable = setTimeout(showElem2, 1600);  
}

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

});

    </script>

`

相关问题