Onclick,只有父div不是细分

时间:2014-03-06 13:53:00

标签: javascript jquery html css modal-dialog

我正在玩建立一个基本的模态窗口,我希望当我点击边缘时它会消失。所以我的问题是最基本的形式:

<div style="width:100%;height:100%;" onclick="hideAll()">
    Hide all onclick.
    <div style="width:100px;height:100px;">
        does not hide all onclick
    </div>
</div>

实现这一目标的最佳方法是什么?使用unnested div? html / css魔术?

5 个答案:

答案 0 :(得分:2)

<强> HTML:

<div style="width:100%;height:100%;" class="outerModal">
    Hide all onclick.
    <div style="width:100px;height:100px;">
        does not hide all onclick
    </div>
</div>

<强> JavaScript的:

$(document).on("click", ".outerModal", function(evt) {  //listen for clicks
    var target = $(evt.target ||evt.srcElement);  //get the element that was clicked on
    if (target.is(".outerModal")) {  //make sure it was not a child that was clicked. 
        //hide dialog
    }
});

示例:

JSFiddle

答案 1 :(得分:1)

当你隐藏父标记时,它也会自动隐藏childen标记,你应该首先将子div包含到变量中,之后隐藏父div并将存储的子div附加到父标记中,就像这样。

<强> HTML

<div id="result">
    <div style="width:100%;height:100%;" id="parentDiv" onclick="hideAll()">
        Hide all onclick.
        <div style="width:100px;height:100px;" id="childDiv">
            does not hide all onclick
        </div>
    </div>
</div>

<强>的javaScript

function hideAll(){
    var childDiv = document.getElementById('childDiv'); //contain child div
    var parDiv = document.getElementById('parentDiv');
    parDiv.style.display = 'none'; //hide parent div
    parDiv.parentNode.appendChild(childDiv); //append child div
}

DEMO

答案 2 :(得分:1)

假设“parentDiv”是背景而“childDiv”是实际的模态内容,我发现的最好方法是完全分开div。

HTML

<div id="parentDiv" onclick="hideAll()">&nbsp;</div>
<div id="childDiv" >
   does not hide all onclick
</div>

使用jQuery的Javascript

function hideAll(){
    /* The Parent Div will hide everything when clicked, but the child won't */
    $('#childDiv').fadeOut(1000, function(){
        $('#parentDiv').fadeOut(1000);
    });
}

CSS

#parentDiv {
    background: black;
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    height: 100%;
    width: 100%;
}

#childDiv { 
    display: block;
    position: relative;
    background: white;
    height: 200px;
    width: 200px;
    z-index: 101
}

Here is a working example.

希望这会有所帮助。

答案 3 :(得分:0)

看到这个小提琴:

http://jsfiddle.net/eZp9D/

$(document).ready(function () {
    $('#parentDiv').click(function (e) {
         if ($(e.target).prop('id') == "parentDiv") {
            $(this).hide();
        }
    });
});

答案 4 :(得分:0)

你可以使用基本的jQuery并使用CSS相应地设置它。 检查this example

如果您希望通过单击对话框窗口外部使其消失,请确保onClick执行此操作:

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