javascript 隐藏 div 模糊
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4629774/
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 on blur
提问by santa
I have a jQuery function where when an element is clicked a hidden div shows.
我有一个 jQuery 函数,当一个元素被点击时,一个隐藏的 div 会显示出来。
$('.openHide').click(function(){
$(this).next('.hiddenContent').toggle();
});
I need to modify it s that I could close this div if I click back not just on the first element. Possibly on Blur, but I am not sure how to indicate the element...
我需要修改它,如果我不仅仅单击第一个元素,我可以关闭这个 div。可能在 Blur 上,但我不确定如何指示元素...
$('.hiddenContent').blur(function() {
$('.hiddenContent').parent().children('.hiddenContent').hide();
});
Here's my HTML:
这是我的 HTML:
<span class="openHide">text here</span>
<div style="display:none" class="hiddenContent">
hidden content here
</div>
回答by Kees C. Bakker
- On the click on the span the div should be toggled
- On the body click the div should be hidden
- On the click on the div, the event should not be propagated to the body
On the click on the span the event should not be propagated to the body
$(document).ready(function() { $('.openHide').click(function(e) { $('.hiddenContent').toggle(); e.stopPropagation(); }); $(document.body).click(function() { $('.hiddenContent').hide(); }); $('.hiddenContent').click(function(e) { e.stopPropagation(); }); });
- 在点击跨度的 div 应该被切换
- 在身体上点击 div 应该被隐藏
- 单击 div 时,不应将事件传播到正文
在跨度上单击时,不应将事件传播到正文
$(document).ready(function() { $('.openHide').click(function(e) { $('.hiddenContent').toggle(); e.stopPropagation(); }); $(document.body).click(function() { $('.hiddenContent').hide(); }); $('.hiddenContent').click(function(e) { e.stopPropagation(); }); });
回答by Marcus Whybrow
If .hiddenContentis a div you won't be able to use blur, that only works on text inputs. mouseoutmay be an alternative, and $(this)is what I think you are looking for in this case:
如果.hiddenContent是 div,您将无法使用模糊,它仅适用于文本输入。mouseout可能是另一种选择,$(this)这就是我认为您在这种情况下正在寻找的:
$('.hiddenContent').mouseout(function() {
$(this).hide();
});
Hide on clicking elsewhere
点击别处隐藏
If you want to hide the div when you click outside the element you must watch for clicks all over the body of the page:
如果要在元素外部单击时隐藏 div,则必须注意整个页面主体的单击:
$('body').click(function() {
// Hide all hidden content
$('.hiddenContent').hide();
});
And then provide and exception for when you are clicking on the actually hidden content itself, and when you want to open it:
然后在您单击实际隐藏的内容本身以及何时打开它时提供和例外:
$('.hiddenContent').click(function(e) { e.stopPropagation() });
$('.openHide').click(function(e) {
$(this).next('.hiddenContent').toggle();
// this stops the event from then being caught by the body click binding
e.stopPropagation();
});

