如何关闭 - 隐藏DIV点击它外面(但不在里面) [英] How to close-hide DIV clicking outside of it (but not inside)

查看:119
本文介绍了如何关闭 - 隐藏DIV点击它外面(但不在里面)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div ,我添加到一个页面,我需要使它当用户点击外面的div,它会隐藏,但不是如果他点击

我尝试使用

e.stopPropagation();



e.preventDefault();

I have a div that i add to a page and i need to make it that when the user clicks outside of that div it will hide, but not if he clicks in side that div, then it should stay.
I tried using
e.stopPropagation();
and
e.preventDefault();

事件的那个特定的div,但没有工作。

adding it to the click event of that certain div but didnt work.

任何人都知道任何好的想法?

any one know of any good ideas?

推荐答案

在弹出式悬停上切换标记

var $pop   = $('#popup'),
    notHov = 1; // Hover flag

$pop.hover(function(){ notHov^=1; }); // Toggle flag on hover

$(document).on('mouseup keyup', function( e ){
  if(notHov||e.which==27) $pop.fadeOut();
});

注意: $ b如果页面上有某个元素阻止 mouseup事件冒泡达到文档(要注册),您可能需要创建全屏(如页面叠加层)弹出式封装容器点击事件,在上面的代码中只改变选择器: $(document)会是 $('#popupWrapper')

Note:
if somewhere on the page you have an element the prevents the mouseup event to bubble up the DOM tree reaching document (in order to be registered), you might want to create a full-screen (like an page-overlay) popup wrapper to register the click events, changing in the code above just the selector: instead of $(document) would be $('#popupWrapper')

这篇关于如何关闭 - 隐藏DIV点击它外面(但不在里面)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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