点击弹出层外部关闭弹出层

4
我是一个编程的入门者。我一直在寻找答案,但没有一个能解决我的问题。我使用了该问题中解释的如何居中javascript css弹出式div,无论屏幕分辨率是什么?的弹出式div方法。
通过对以下代码进行小改动,是否有可能通过单击其外部区域来关闭一个div?
<script type="text/javascript">
    function showPopUp(el) {
        var cvr = document.getElementById("cover")
        var dlg = document.getElementById(el)
        cvr.style.display = "block"
        dlg.style.display = "block"
        if (document.body.style.overflow = "scroll") {
            cvr.style.width = "1024"
            cvr.style.height = "100%"
        }
    }
    function closePopUp(el) {
        var cvr = document.getElementById("cover")
        var dlg = document.getElementById(el)
        cvr.style.display = "none"
        dlg.style.display = "none"
        document.body.style.overflowY = "scroll"
    }
</script>
<style type="text/css">
   #cover {
        display:        none;
        position:       fixed;
        left:           0px;
        top:            0px;
        width:          100%;
        height:         100%;
        background:     gray;
        filter:         alpha(Opacity = 50);
        opacity:        0.5;
        -moz-opacity:   0.5;
        -khtml-opacity: 0.5
    }

</style>

在HTML中,我隐藏了具有ID dialog1dialog2等的多个

元素。当用户点击链接时,这些元素会显示出来,为了关闭它们,我使用了一个链接:

< a class="close" href="#2" onclick="closePopUp('dialog2');">< img src="/img/close.png" height="30px"></a >

1
发布你的代码以获得答案。 - Kingk
代码在我发布的链接中! - Kristine
作为初学者,您需要一种在文档上注册鼠标单击事件并从那里关闭弹出窗口的方法。没有您的代码,我只能做到这一步。 - Mark Walters
我正在使用链接中的相同代码!但是我会在这里发布它!谢谢! - Kristine
4个回答

9
当您打开弹出窗口时,请创建一个高度为100%的不可见div,该div位于您的弹出窗口div后面。
将onclick功能附加到该div:
document.getElementById('invisibleDiv').onclick = function()
{
    document.getElementById('popup').style.display = 'none'; 
}

希望这能帮到你。

非常感谢!我会在检查后回复您! - Kristine
嘿!非常感谢,它起作用了!我尝试了两种方法,第一种是:我为每个div添加了closePopUp函数到#cover中,但那太长了,你的方法更好!抱歉现在才回复! - Kristine
完成了!我只能接受,不能点赞,因为我最近才开始使用这个网站!感谢您的时间和知识! - Kristine

4
var $popup = $('#your-popup');

$('body').on('click', function(ev) {
   $popup.hide(); // click anywhere to hide the popup; all click events will bubble up to the body if not prevented
});

$popup.on('click', function(ev) {
   ev.stopPropagation(); // prevent event from bubbling up to the body and closing the popup
});

这是一个优雅的解决方案,但是您的文档监听器将不再在弹出窗口内工作。例如,我有 $(document).on('click', '.btn-delete', function() {confirm('really delete this?')}); - William Randokun
@WilliamRandokun 是的...它并不完美。如果你有一个背景,把点击处理程序放在上面会更容易。 - mpen

0

使用JavaScript而不创建一个隐藏的div:

添加以下内容:

function getOffset(el) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

// function to check intersection rectangle <-> point
function intersects(ax1, ay1, ax2, ay2, px, py) {
    return !(ax2 < px || ax1 > px || ay2 < py || ay1 > py);
}

document.onclick = function(event) {
    var dialog = document.getElementById('dialog');
    var offset = getOffset(dialog);
    var ax1 = offset.left;
    var ay1 = offset.top;
    var ax2 = ax1 + 300 /* dialog width */;
    var ay2 = ay1 + 300 /* dialog height */;

    if(!intersects(ax1, ay1, ax2, ay2, event.pageX, event.pageY)) {
        closePopUp('dialog');
    }
};

避免使用不可见的div看起来很有趣,但是,如果页面中的某个元素停止了事件的传播,那么它会破坏弹出窗口的自动关闭功能,不是吗? - Alvaro Rivoir

0

是的...很重要的是在使用Jquery 2.0.0.js时删除覆盖层,即<div class="ui-widget-overlay ui-front"></div>...(也许在之前的库中名称有所更改)

例如...

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>

    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
</head>
    <script type="text/javascript">
// <---- VENTAÑAS DE PARAMETERES---->
$(document).ready(function() { 
$( "#wnd_Paramedit" ).dialog({
                autoOpen: false,
                height: 'auto',
                width: 405,
                modal: true,
                resizable:false,
                buttons: {
                    "Accept": function() {


                        $( this ).dialog( "close" );    
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
                    $( this ).dialog( "close" );
                }
            });

            $( "#btn_Pedit" ).click(function() {
                    $( "#wnd_Paramedit" ).dialog( "open" );
$("div").removeClass("ui-widget-overlay ui-front");
                });
});
</script>
<body>
<h3>List of parameters</h3>
<div id="sortparam" >


</div>
<input type="button" id="btn_Pedit" value="Edit"/>
<div id="wnd_EditParam" title="Edit Parameter"></div>
</body>
<div id="wnd_Paramedit" title="Choose parameter" >
    <label> inserta el nombre del Parameter que quiere modificar<label><br />
    <label> ID <input type=text size=30 id="med"></label>      
</div>
</html>

现在,您可以创建另一个特定的按钮来关闭弹出窗口,并将以下特定代码粘贴以关闭:

$( "#wnd_Paramedit" ).dialog("close");

或者

$( "#wnd_Paramedit" ).dialog("destroy");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接