javascript通过单击外部隐藏div

标签 javascript html css

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

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

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

这两个函数都有效,但即使我在其中单击“welcomeDiv”,它也会隐藏(因为“welcomeDiv”是容器 DIV 的一部分)。因此,当在“welcomeDiv”中单击 happends 时,我需要禁用 hideDiv() 函数。 就像是: <div id='welcomeDiv' onclick='hideDiv().disable'>

但是我不知道怎么写才正确,试了很多东西。 期待,提前致谢

最佳答案

为您演示解决方案的简单 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>

关于javascript通过单击外部隐藏div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28458246/

相关文章:

javascript - 使用 jQuery 无限滚动静态页面

javascript - jQuery jScrollPane 插件 IE 8 滚动对于大数据/内容非常慢

html - 如果图像被使用 N 次,是否会在 HTML 页面上下载 N 次?

javascript - 为什么相同输入字段文本中的 `readonly` 、 `disabled` 和 `required` 无法正常工作?

html - 删除 <div> 元素上方和下方的边距?

html - Bootstrap 4 分页缩放/响应能力

internet-explorer-7 - border-radius.htc 使边框变圆,但不是图像

javascript - 这两个代码片段之间有什么真正的区别吗?

javascript - JavaScript 可排序 html 表格的问题

c# - 从另一个项目/dll 引用的 Asp.NET 用户控件具有 NULL 属性