如何在元素之外的任何位置隐藏单击事件上的元素? [英] How do I hide an element on a click event anywhere outside of the element?

查看:23
本文介绍了如何在元素之外的任何位置隐藏单击事件上的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是否是在单击页面上的任何位置时隐藏可见元素的正确方法.

I would like to know whether this is the correct way of hiding visible elements when clicked anywhere on the page.

$(document).click(function (event) {            
    $('#myDIV:visible').hide();
});

在元素边界内发生点击事件时,元素(div、span 等)不应消失.

The element (div, span, etc.) shouldn't disappear when a click event occurs within the boundaries of the element.

推荐答案

如果我明白,当你点击除 div 之外的任何地方时你想隐藏一个 div,如果你在 div 上点击,那么它不应该关闭.你可以用这个代码做到这一点:

If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

这会将点击绑定到整个页面,但是如果您点击有问题的 div,它将取消点击事件.

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.

这篇关于如何在元素之外的任何位置隐藏单击事件上的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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