点击Inside Div时隐藏Div

时间:2015-02-27 20:59:56

标签: javascript html hide

我有这个代码,当你点击某个东西时,会出现一个隐藏的div,但让div消失的唯一方法就是点击它之外。我想知道是否有办法让它能够点击div本身使它消失。

爪哇:

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:

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

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>

2 个答案:

答案 0 :(得分:1)

您只需在div叠加层上添加相同的切换调用:

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

<强> jsFiddle example

答案 1 :(得分:0)

添加onclick功能。

HTML:

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

JavaScript的:

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

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

jsfiddle sample

如果您想在两个分隔线之间进行替换,请参阅this example