简体   繁体   中英

scrolling div using jquery setTimeout & mouseenter & mouseleave

I have a div container which sticks to the bottom of the page. When the mouse moves out of the div, I want the div to sink after 3 seconds. When the mouse moves over the div, I want the div to rise to its original position. 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.

   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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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