问题描述:

I have a set of divs in my HTML document and use jQuery to show them one by one after every 15000ms. I would also like to include some links inside some of the divs so I want to pause or delay the div on hover. Here is my script code. Can somebody show me how to pause on hover?

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

网友答案:

You can clear the timeout on mouseover and start it again on mouseout. I updated your code:

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)
  });
});

Probably not the best solution code-wise, but the key here is clearTimeout() which let's you cancel a timeout set with setTimeout().

网友答案:

I believe you can tie the Timeout to a variable so you can cancel it on hover, then just reload the function on mouse out. This isn't tested but I think this should work: :`

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

`

相关阅读:
Top