我有两个函数的 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/