第二次按下后,Jquery动画“打开”和“关闭”

时间:2013-11-21 16:49:18

标签: jquery

当我点击a_demo_threee div时,我会点击Document 它关闭;到目前为止一切都那么好,但是当我第二次打开它并立即关闭时。现在我想知道问题是什么以及如何解决它。

以下是Jquery代码,请仔细查看此JSFiddle

$(".a_demo_threee").click(function () { //opens the login

$(".a_demo_threee").animate({
    "width": "300px",
    "height": "200px",
}, 1000);

$("#contentlogin").show();
timer = setTimeout(closelogin, 1);
});

function closelogin() {
clearTimeout(timer);
$(document).click(function () {
    $(".a_demo_threee").animate({
        "width": "42px",
        "height": "39px",
    }, 1000);

    $("#contentlogin").hide();
});}

2 个答案:

答案 0 :(得分:1)

问题是您要添加两个点击处理程序:一个用于展开/显示,另一个用于最小化/隐藏。我会重构代码,所以有一个单击处理程序,如果它被隐藏,则扩展div,如果显示则最小化它。见下文和工作小提琴:http://jsfiddle.net/HQS8s/97/

$("#contentlogin").hide(); //hides the content so its invisibil on the refresh/load of the website

$(".a_demo_threee").click(function () {
    if ($("#contentlogin:hidden").length > 0) {
        openLogin();
    } else {
        closeLogin();
    }
});

function openLogin() {
    $(".a_demo_threee").animate({
        "width": "300px",
        "height": "200px",
    }, 1000);
    $("#contentlogin").show();
}

function closeLogin() {
    $(".a_demo_threee").animate({
        "width": "42px",
        "height": "39px",
    }, 1000);
    $("#contentlogin").hide();
}

答案 1 :(得分:0)

为什么你复杂化(设定一个时间并清除它)。简单的事情。实际上event bubbling是您的代码当前面临的问题。您可以使用event.stopPropagation阻止事件从anchor元素冒泡到document

请阅读:event.stopPropagation

$(".a_demo_threee").click(function (e) { //opens the login

    e.stopPropagation();

    $(".a_demo_threee").animate({
        "width": "300px",
        "height": "200px",
    }, 1000);

    $("#contentlogin").show();
});

    $(document).click(function () {
        $(".a_demo_threee").animate({
            "width": "42px",
            "height": "39px",
        }, 1000);

        $("#contentlogin").hide();
    });

DEMO


您可以使用.stop()功能清除动画队列。

DEMO I

相关问题