javascript 单击外部时隐藏 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14652712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
hide div when click outside
提问by Ljubo Valevski
I am using a simple javascript code to toggle div onclick. You can see it in action on this link: k-prim.biz/Untitled-2.html - it is a quite simple demo page. What I want to make is to hide div not only when click on the "link" but also when click outside the div. Also how can I change the css style of the "link" when the div is displayed? Thank you in advance!
我正在使用一个简单的 javascript 代码来切换 div onclick。您可以在此链接上看到它的实际效果:k-prim.biz/Untitled-2.html - 这是一个非常简单的演示页面。我想要做的是不仅在单击“链接”时隐藏 div,而且在单击 div 外时也隐藏 div。另外,如何在显示 div 时更改“链接”的 css 样式?先感谢您!
<script type="text/javascript" language="javascript">
function showHide() {
var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block"; }
}
</script>
<a href="#" onClick="return showHide();" >link</a>
<div id="showHideDiv" style="display:none;">hello!</div>
回答by Elliot Bonneville
You've not given me any code to work with, so you'll have to modify this to suit your needs:
你没有给我任何代码来使用,所以你必须修改它以满足你的需要:
$(document).click(function() {
if(this != $("#the_div")[0]) {
$("#the_div").hide();
}
});
That will hide the div if a user clicks anywhere on the page that isn't that div.
如果用户点击页面上不是那个 div 的任何地方,这将隐藏 div。
回答by Raj-887
HTML:
HTML:
<div id="settings">
<input/><select></select><span>text</span>
</div>
Javascript:
Javascript:
var settings = document.getElementById('settings');
document.onclick = function(e){
var target = (e && e.target) || (event && event.srcElement);
var display = 'none';
while (target.parentNode) {
if (target == settings) {
display ='block';
break;
}
target = target.parentNode;
}
settings.style.display = display;
}
回答by theshadowmonkey
This is a quick hack I wrote. I am not sure why you want to do the same activity by clicking anywhere on the document. If you want to do that, replace jQuery('#link') with jQuery(document).
这是我写的一个快速黑客。我不确定您为什么要通过单击文档上的任意位置来执行相同的操作。如果您想这样做,请将 jQuery('#link') 替换为 jQuery(document)。
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
jQuery('#link').click(function(){
if(jQuery('#showHideDiv').hasClass('hide')) {
jQuery('#showHideDiv').removeClass('hide');
jQuery('#link').css('color', 'red');
} else {
jQuery('#showHideDiv').addClass('hide');
jQuery('#link').css('color', 'blue');
}
});
});
</script>
</head>
<body>
<a href="#" id="link" >link</a>
<div id="showHideDiv" class="hide">hello!</div>
</body>
</html>
This is the link to the jsfiddle
这是jsfiddle的链接
and also add css rule
并添加css规则
.hide {
display:none;
}