jQuery - Animation transition interrupted by hover

杀马特。学长 韩版系。学妹 提交于 2020-02-06 03:11:24

问题


I have created a div to slide in from outside of the viewport and place itself over the original div.

The animation is triggered by hovering over box1. This will bring box2 in place of box1.

When the mouse leaves the box2 div, it will be placed outside of the viewport again.

However, slow cursor movement within this div will result in animation triggering rapidly.

 $(document).ready(function() {
$('.box1').mouseover(function() {
    $('.box2').stop().animate({
        top: 0
    }, 100);
}).mouseout(function() {
    $('.box2').stop().animate({
        top: '-200px'
    }, 100);
});
});

The following fiddle should present the problem.

http://jsfiddle.net/B9wx8/


回答1:


Do like this, Bind event for both elements, it would solve the issue

$(document).ready(function () {
    $('.box1,.box2').mouseenter(function () {
        $('.box2').stop().animate({
            top: 0
        }, 'slow');
    }).mouseleave(function () {
        $('.box2').stop().animate({
            top: '-200px'
        }, 'slow');
    });
});

DEMO




回答2:


You could do something like this:

var done = true;
$(document).ready(function() {
    $('.box1').mouseenter(function() {
        if (done){
            done = false;
            $('.box2').stop().animate({
                top: 0
            }, {duration: 400,
                complete: 
                    function(){
                        done = true
                    }
                 });
        }
    });
    $('.box2').mouseleave(function() {
        if (done){            
            done = false;
            $('.box2').stop().animate({
                top: -400
            }, {duration: 400,
                complete: 
                    function(){
                        done = true
                    }
                 });
        }
    });
});

So check if the animation is still going, and only if not start the next one



来源:https://stackoverflow.com/questions/24712501/jquery-animation-transition-interrupted-by-hover

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!