用相同的按钮关闭模态

时间:2015-03-11 20:27:29

标签: jquery css modal-dialog

我使用以下jquery弹出全屏叠加模式。我的菜单具有更高的z-index,因此它始终位于所有内容之上。问题是,我希望能够使用启动它的相同按钮关闭我的模态。现在它只是重新加载模态。我试图更改$("a[rel=modal]”)所以它close(modalId);,但无济于事。感谢。

http://jsfiddle.net/Ld6c2pe2/,代码:

(function( $ ){

$.fn.modal = function() {
    var t = Math.floor($("body").scrollTop());
    var bg = $("<div id='modal-bg'></div>");
    $("body").append(bg);
    $("#modal-bg").css({
        "position": "fixed",
        "background": "rgba(0,0,0,0.7)",
        "top": 0,
        "left": 0,
        "height": "100%",
        "width": "100%",
        "z-index": 100,
        "opacity": 0
    });
    $("#modal-bg").fadeTo(200, 1);

    var modalId = $(this).attr("href");
    $(modalId).css({
        'display': 'block',
        'position': 'fixed',
        'left': (($(window).width() - $(modalId).outerWidth()) / 2),
        'top': (($(window).height() - $(modalId).outerHeight()) / 2),
        'opacity': 0,
        'z-index': 200
    });
    $(modalId).fadeTo(200, 1);
    $(window).scrollTop(t - (($(window).height() - $(modalId).outerHeight()) / 2) + 1);

    $("#modal-bg").click( function() {
        close(modalId);
    });
};

$("a[rel=modal]").click( function() {
    $(this).modal();
});

function close(id){
    $(id).css('display', 'none');
    $("#modal-bg").fadeOut(200);
    setTimeout( function() {$("#modal-bg").remove();}, 200);
};

})( jQuery );

1 个答案:

答案 0 :(得分:0)

为什么不检查点击事件中DOM中是否有模态?

http://jsfiddle.net/Ld6c2pe2/1/

$("a[rel=modal]").click( function() {
    if ($("#modal-bg").length) {
        close();
    } else {
        $(this).modal();
    }
});