Javascript 切换 - 在 div 外单击时隐藏项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13831064/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:52:02  来源:igfitidea点击:

toggle- hide item when click outside of the div

javascriptjquery

提问by olo

I am using jquery's slidetoggle, want to learn how to make the showupclass hide when click anywhere outside of the DIV. thanks!

我正在使用 jquery 的 slidetoggle,想学习如何showup在单击 DIV 外的任何地方时隐藏类。谢谢!

Online SAMPLE: http://jsfiddle.net/evGd6/

在线样本:http: //jsfiddle.net/evGd6/

<div class="click">click me</div>
<div class="showup">something I want to show</div>?
$(document).ready(function(){
    $('.click').click(function(){
        $(".showup").slideToggle("fast");
    });
});?
.showup {
    width: 100px;
    height: 100px; 
    background: red; 
    display:none;
}
.click {
    cursor: pointer;
}
    ?

回答by Sampson

Stop event propagation from within the .showuparea:

停止.showup区域内的事件传播:

$(document).on("click", function () {
    $(".showup").hide();
});

Then prevent those clicks on .showupfrom bubbling up to the document:

然后防止这些点击.showup冒泡到document

$(".showup").on("click", function (event) {
    event.stopPropagation();
});

Any click event that reaches the documentwill result in the .showupelement being hidden. Any click events that start from within .showupwill be prevented from proceeding any further up the DOM tree, and thus will never reach the document.

任何到达 的点击事件document都会导致.showup元素被隐藏。任何从内部开始的点击事件都.showup将被阻止在 DOM 树中进一步向上进行,因此永远不会到达document.

You will also need to stop any clicks on your button from traveling up to the documentas well:

您还需要停止对您的按钮的任何点击移动到document

$(".click").on("click", function (event) {
    event.stopPropagation();
    $(".showup").slideToggle("fast");
});

Otherwise that click event will bubble up to the documentand result in the hiding of .showupimmediately.

否则那个点击事件会冒泡到document并导致.showup立即隐藏。

Demo: http://jsfiddle.net/evGd6/2/

演示:http: //jsfiddle.net/evGd6/2/

回答by Botea Florin

If you still want to record clicks on .showuppanel (lets say you want it to be more then a simple informative panel), calling event.stopPropagation()on clicking it will make that panel untouchable/useless. Use event.cancelBubble = trueinstead and will let the event occur on .showupchilds.

如果您仍想记录.showup面板上的点击次数(假设您希望它不仅仅是一个简单的信息面板),则调用event.stopPropagation()点击它将使该面板无法触及/无用。使用event.cancelBubble = true来代替,而让事件发生在.showup孩子的。

$('.click').click(function(){
    $(".showup").toggle();
});

$(".showup").on("click", function (/*nothing here*/) {
    event.cancelBubble = true
});

$(document).on("click", function () {
    $(".showup").hide();
});