仅在选项卡未滑出时进行动画处理

时间:2013-10-09 08:20:22

标签: jquery jquery-animate

我有这个标签滑块,当你悬停标签时它会移动一点。我希望只有当滑块没有滑出时才会发生这种情况。当它出来时它不应该继续悬停。 See working example here

当滑块滑出时,滑块会使类“打开”,所以我尝试添加此代码:

if (!$("#contactContainer").hasClass("open")) {
    $("#contactContainer").hover(function() {
        $(this).stop(true, true).animate({
        "right": "+=30px"
    }, 300); }, function() {
        $(this).stop(true, true).animate({
        "right": "-=30px"
    }, 300); });
}

然而,它似乎没有任何区别。悬停时,打开的滑块仍会移动。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:3)

您正在做的只是在容器未打开时添加悬停功能 - 因为这在加载时发生(当容器未打开时),悬停功能始终存在。

这有几种方法,最简单的方法是在容器打开时检查悬停功能,试试这个:

$("#contactContainer").hover(
    function() {
        if (!$(this).hasClass("open")) {
            $(this).stop(true, true).animate({"right": "+=45px"}, 300);
        }
    }, function() {
        if (!$(this).hasClass("open")) {
            $(this).stop(true, true).animate({"right": "-=45px"}, 300);
        }
    }
);

或者实现一个封闭的类,并直接在该类上使用CSS动画来进行移动。或者添加/删除悬停功能作为打开/关闭功能的一部分。上述解决方案最简单,但可能会有一些问题,具体取决于您想要的确切功能。

答案 1 :(得分:2)

使用SpaceDog的示例,滑块关闭但继续为屏幕外设置动画。这是因为'open'类被立即删除,当鼠标悬停在容器上时,触发悬停行为(将屏幕左侧的标签移动45个像素,并阻止用户再次单击它)。 / p>

如果您同时检查':animated'属性,则可以阻止悬停行为的触发,从而将标签保留在屏幕上:

$("#contactContainer").hover(
    function() {
    if (!$(this).hasClass("open") && !$(this).is(":animated")) {
        $(this).stop(true, true).animate({"right": "+=45px"}, 300);
    }
    }, function() {
        if (!$(this).hasClass("open") && !$(this).is(":animated")) {
            $(this).stop(true, true).animate({"right": "-=45px"}, 300);
        }
    }
);

答案 2 :(得分:0)

你必须将if语句移动到你的悬停函数中,并且只有在它没有打开类时才动画。

您的if check目前仅在加载页面时检查容器。

答案 3 :(得分:0)

您也可以使用on-method of jQuery。这将绑定到文档的mouseenter和mouseleave元素,然后检查它们是否从与选择器匹配的元素冒泡。

$(document).on("mouseenter", "#contactContainer:not(.open)", function() {
    $(this).stop(true, true).animate({"right": "+=45px"}, 300);
}).on("mouseleave", "#contactContainer:not(.open)", function() {
    $(this).stop(true, true).animate({"right": "-=45px"}, 300);
});