简体   繁体   English

在Div内单击时隐藏Div

[英]Hiding Div When Clicking Inside Div

I have this code that when you click on something, a hidden div appears, but the only way to get the div to disappear is to click outside of it. 我有这段代码,当您单击某项时,将显示一个隐藏的div,但是使div消失的唯一方法是在其外部单击。 I was wondering if there was a way to make it so that you're able to click the div itself to make it disappear. 我想知道是否有一种方法可以使您能够单击div使其消失。

Java: Java的:

function toggle() {
var ele = document.getElementById("about");
//var text = document.getElementById("displayText");
if(ele.style.display == "block") {
    ele.style.display = "none";
    //text.innerHTML = "show";
}
else {
    ele.style.display = "block";
    //text.innerHTML = "hide";
}
}

CSS: CSS:

#about {height: 100%; width: 100%; background: rgba(0, 0, 0, 0.6); position: fixed; bottom: 0px; left: 0px;}

HTML: HTML:

<a id="displayText" href="javascript:toggle();"><img src="http://companionplants.com/images/small-plant2.jpg"></a>

<div id="about" style="display: none;">
Text here
</div>

You can just add the same toggle call on the div overlay itself: 您可以在div叠加层本身上添加相同的切换调用:

<div id="about" onclick="toggle()" style="display: none;">Text here</div>

jsFiddle example jsFiddle示例

Add an onclick function. 添加一个onclick函数。

HTML: HTML:

<div id="mainDiv">
    testing
</div>

JavaScript: JavaScript的:

var mainDiv = document.getElementById('mainDiv');

mainDiv.style.cursor = 'pointer';
mainDiv.onclick = function() {
    mainDiv.style.display = "none";
}

jsfiddle sample jsfiddle示例

If you want to alternative between two dividers, then see this example . 如果要在两个分隔线之间进行替换,请参见此示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM