检查第一个事件是否发生,但第二个事件没有发生



我有一个代码,如果我对li元素进行mousenter,它的高度将增加,其他两个LIS高度将降低。

$("li").mouseover(function(){   
var thisName    =   $(this).attr("name"),
    lis         =   [];
    lis[0]      =   $("li[name=first]");
    lis[1]      =   $("li[name=second]");
    lis[2]      =   $("li[name=third]");
$(this).animate({
    height: "200px"
}); 
for(i=0; i<lis.length; i++) {
    if(lis[i].attr("name")!=thisName) {
        lis[i].animate({
            height: "50px"
        });
    };
};  
});

我也有用于Mouseleave的代码。那将把这三个李的高度归还到100px。

当我鼠标鼠标,而不是进入另一个LI元素时,一切都可以。

但是,如果我从李元素中慕斯,然后将鼠标捕捞到另一个,我会有问题。然后:第一个MouseLeave事件将起作用,并将每个LI将每个LI调整为100px,然后将Mouseenter事件起作用。

这看起来很漂亮。我想在发生Mousenter或Mouse休假事件时取消所有其他动画。

您可以使用.stop(true)停止动画

$("li").mouseover(function () {
    var thisName = $(this).attr("name"),
        lis = [];
    lis[0] = $("li[name=first]");
    lis[1] = $("li[name=second]");
    lis[2] = $("li[name=third]");
    //use .stop(true)
    $(this).stop(true).animate({
        height: "200px"
    });
    for (i = 0; i < lis.length; i++) {
        if (lis[i].attr("name") != thisName) {
            lis[i].stop(true).animate({
                height: "50px"
            });
        };
    };
});

可以像

一样清理您的代码
var $lis = $("li").mouseover(function () {
    //use .stop(true)
    $(this).stop(true).animate({
        height: "200px"
    });
    $lis.not(this).stop(true).animate({
        height: "50px"
    });
});

您也可以使用.hover()注册MouseEnter和Mouseleave处理程序,例如

var $lis = $("li").hover(function () {
    //use .stop(true)
    $(this).stop(true).animate({
        height: "200px"
    });
    $lis.not(this).stop(true).animate({
        height: "50px"
    });
}, function () {
    $lis.stop(true).animate({
        height: "100px"
    });
});

演示:小提琴

最新更新