简体   繁体   English

使用jQuery setTimeout滚动div和mouseenter和mouseleave

[英]scrolling div using jquery setTimeout & mouseenter & mouseleave

I have a div container which sticks to the bottom of the page. 我有一个div容器,它粘在页面底部。 When the mouse moves out of the div, I want the div to sink after 3 seconds. 当鼠标移出div时,我希望div在3秒后下沉。 When the mouse moves over the div, I want the div to rise to its original position. 当鼠标移到div上时,我希望div升至其原始位置。 The problem is when the mouse moves over and out of the div very quickly, the div keeps moving up towards the top of the page. 问题是,当鼠标非常快地移入和移出div时,div会继续向上移动到页面顶部。

   var timer = null;
   var moving_distance = $("#scroller").height()-($(window).height()-$("#slideshow").height());
   $("#scroller").mouseenter(function(event){

    if(timer)
    {
     clearTimeout(timer);

         $("#scroller").animate({top:'-='+moving_distance},1000);

    }

}).mouseleave(function(event){

    if(!timer){

    timer = setTimeout(function(){

        $("#scroller").animate({top:'+='+moving_distance},1000);
    },3000);
    }
}); 

I have had success stacking a null animation in front of the animation I want rather than using setTimeout. 我已经成功地在想要的动画之前堆叠了一个空动画,而不是使用setTimeout。

For instance, 例如,

 var moving_distance = $("#scroller").height()-($(window).height()-$("#slideshow").height()); 
 var firstEnter = true;
 $("#scroller").mouseenter(function(event){ 
    if (firstEnter)
        firstEnter = false;
    else {
        $("#scroller").stop();
        $("#scroller").animate({top:'+=0', 3000);
        $('#scroller').animate({top:'-='+$('#scroller').top()), 1000);
    }
}).mouseleave(function(event){ 
    $('#scroller').stop();
    $("#scroller").animate({top:'+=0', 3000);
    $('#scroller').animate({top:'+='+moving_distance), 1000);
});  

I am guessing from your description that you want the div to stand still until the mouse is moved into the div. 我从您的描述中猜测,您希望div静止不动,直到将鼠标移到div中为止。 Then when the mouse leaves for the first time it should sink. 然后,当鼠标第一次离开时,它应该下沉。 After that, when the mouse comes back again, it should return to its original position. 此后,当鼠标再次返回时,它应返回到其原始位置。 I think this will be close to doing that. 我认为这将接近做到这一点。

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM