开发者

js/jQuery - exit function by mouse position

开发者 https://www.devze.com 2023-03-02 02:16 出处:网络
I have a recursive function for a kind of image slider. function nextCol(col) { $(\'.menubox_col\').fadeOut();

I have a recursive function for a kind of image slider.

function nextCol(col) {
  $('.menubox_col').fadeOut();
  $('.menubox_col').eq(col).fadeIn(function(){
    col++;  
    if (col > 3) col = 0;
    setTimeout(function(){ nextCol(col) }, 1000);  
  });
}

<div id="menubox">      
        <div class="menubox_col">content</div>
        <div class="menubox_col">cont开发者_JAVA技巧ent</div>
        <div class="menubox_col">content</div>
        <div class="menubox_col">content</div>
</div>

This works fine, but I found no way to stop the recursive function when the mouse cursor enters the #menubox div.


While you could use clearTimeout and then restart the animation again, you could simply set a flag, which means you don't need to stop and start timers... This will stop the animation when the mouse is over the menubox, and continue it when it leaves. I also took the liberty of making some small code changes - I find the result much simpler:

$(function(){

  var col = 0, hover = false;

  function nextCol() {
    if(hover){return;} // if their mouse is over, do nothing
    col = (col+1) % 4; // make this a one-liner. the 4 probably shouldn't be hard-coded though, it could be $('.menubox_col').length
    $('.menubox_col').fadeOut().eq(col).fadeIn();
  }

  setInterval(nextCol, 1000);

  $('#menubox').hover(function(){ hover=true; }, function(){ hover=false; });

});


You could clear the timeout using clearTimeout:

var timeoutHandle = null;

function nextCol(col) {
    $('.menubox_col').fadeOut();
    $('.menubox_col').eq(col).fadeIn(function() {
        col++;  
        if (col > 3) { col = 0; }
        timeoutHandle = setTimeout(function() { 
            nextCol(col);
        }, 1000);  
    });
}

$('#menubox div').mouseenter(function() {
    window.clearTimeout(timeoutHandle);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号