javascript通过单击外部隐藏div [英] javascript hide div by clicking outside

查看:55
本文介绍了javascript通过单击外部隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the javascript with 2 functions: 1) Show DIV (welcomeDiv) ONCLICK the button; 2) Hide div by clicking on the container DIV (outside of 'welcomeDiv').

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

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

这两个函数都有效,但即使我在里面点击它也会隐藏'welcomeDiv' (因为'welcomeDiv'是容器DIV的一部分)。所以我需要在'welcomeDiv'中点击发生时禁用hideDiv()函数。
类似于:
< div id ='welcomeDiv'onclick ='hideDiv()。disable'>

Both functions work, but 'welcomeDiv' is hiding even when I click inside it (because, 'welcomeDiv' is the part of the container DIV). So I need to disable hideDiv() function when click happends inside of 'welcomeDiv'. Something like: <div id='welcomeDiv' onclick='hideDiv().disable'>

但是我不知道如何正确地写它,尝试了很多东西。
期待,提前谢谢

But I don't know how to write it correctly, tryed many things. Looking forward, thanks in advance

推荐答案

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

Simple html file to demo a solution for you:

<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>

这篇关于javascript通过单击外部隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆