javascript通过单击外部隐藏div

时间:2015-02-11 15:34:40

标签: javascript html css

我有两个函数的javascript: 1)显示DIV(welcomeDiv)ONCLICK按钮; 2)通过单击容器DIV(在' welcomeDiv'之外)隐藏div。

 function showDiv() {
        document.getElementById('welcomeDiv').style.display = "block";
        }

 function hideDiv() {
        document.getElementById('welcomeDiv').style.display = "none";
        }

这两项功能都有效,但欢迎使用这些功能。即使我在里面点击它也会隐藏(因为,&#39; welcomeDiv&#39;是容器DIV的一部分)。因此,我需要在点击“欢迎直播”内的活动时禁用hideDiv()函数。 就像是:                      <div id='welcomeDiv' onclick='hideDiv().disable'>

但我不知道如何正确地写它,尝试了很多东西。 展望未来,先谢谢

3 个答案:

答案 0 :(得分:2)

简单的html文件,为您演示解决方案:

<html>
    <head>
        <title>Test</title>
        <style type="text/css">
            .container { width: 400px; height: 280px; background-color: #e5e5e5;}
            #welcomeDiv { width: 100px; height: 100px; background-color: #b0b0b0; }
        </style>
    </head>
    <body>

        <div class="container" onclick="hideDiv();">
            <button onclick="showDiv();">
                Hello
            </button>

            <div id="welcomeDiv">
                <h1>Welcome</h1>
            </div>
        </div>

        <script type="text/javascript">
            function showDiv() {
                document.getElementById('welcomeDiv').style.display = "inherit";
                event.stopPropagation();
                // stop propagation on button click event
            }

            function hideDiv() {
                var target = event.target || event.srcElement;
                // filter event handling when the event bubbles
                if (event.currentTarget == target) {
                    document.getElementById('welcomeDiv').style.display = "none";
                }

            }
        </script>
    </body>
</html>

答案 1 :(得分:0)

可能:

<div id='welcomeDiv' onclick='showDiv()'>

答案 2 :(得分:0)

您需要访问的是JavaScript“事件”对象。此对象将包含有关已发生事件的信息,在本例中为“MouseEvent”。您可以使用该数据通过查看“target”属性来确定单击了哪个元素。通过为您的包含DIV提供ID,我们可以使用它来过滤掉不需要的点击次数:

HTML:

<div id="welcomeContainer" onclick="showDiv(event)" style="border: 3px solid red;">
Outer Div
<div onclick="hideDiv(event)" id="welcomeDiv" style="border: 3px solid blue;">Inner Div</div>

JavaScript的:

function showDiv(event) {
    if(event.target.id === "welcomeContainer"){
        document.getElementById('welcomeDiv').style.display = "block";
    }
}

function hideDiv(event) {
    document.getElementById('welcomeDiv').style.display = "none";
}

这是一个显示工作代码的小提琴:http://jsfiddle.net/fmz2h6kj/