切换 - 在div外部单击时隐藏项目 [英] toggle- hide item when click outside of the div

查看:78
本文介绍了切换 - 在div外部单击时隐藏项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery的slidetoggle,想要了解如何在点击DIV之外的任何地方时隐藏 showup 类。
谢谢!

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

在线样本: 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;
}
    ​


推荐答案

停止事件传播来自 .showup 区域:

Stop event propagation from within the .showup area:

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

然后阻止 .showup 上的点击冒泡到文件

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

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

任何到达文件的点击事件都将导致隐藏 .showup 元素。从 .showup 开始的任何点击事件都将被阻止继续进行DOM树的任何进一步上升,因此永远不会到达文档

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

您还需要停止对按钮的任何点击,直至文件以及:

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

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

否则点击事件将冒泡到文件并立即隐藏 .showup

Otherwise that click event will bubble up to the document and result in the hiding of .showup immediately.

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

这篇关于切换 - 在div外部单击时隐藏项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆