如何在点击外部时关闭/隐藏DIV元素(但不在里面) [英] How to close/hide a DIV element when clicking outside of it (but not inside)

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

问题描述

我有一个存在于页面上的< div> ,我需要这样做,以便当用户点击该元素外部时,它将变为隐藏,但如果用户点击元素内的某个地方,那么它应该保留。



我尝试使用

e.stopPropagation() ;




e.preventDefault();



将它添加到某个DIV的click事件中,但是没有奏效。

谢谢!

解决方案

在弹出悬停上切换标志 http://jsbin.com/Close_Modal_ESC_or_Click/3/editrel =nofollow> JSBin demo

  var $ pop = $('#popup'),
notHov = 1; //悬停标志

$ pop.hover(function(){notHov ^ = 1;}); //悬停的切换标志
$ b $(document).on('mouseup keyup',function(e){
if(notHov || e.which == 27)$ pop。 fadeOut();
});

注意:

如果页面某处有一个元素,阻止 mouseup事件冒泡达到文档的DOM树(为了注册),您可能需要创建全屏(如页面叠加)弹出包装以注册点击事件,改变上面的代码只是选择器:而不是 $(document)会是 $('#popupWrapper')


I have a <div> that exists on a page and I need to make it so that when the user clicks outside of that element it will become hidden, but if the user clicks somewhere within the element, then it should stay.

I tried using
e.stopPropagation();
and
e.preventDefault();

adding it to the click event of that certain DIV but that didn't work.

Thanks!

解决方案

Toggle a flag on popup hover:

JSBin demo

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();
});

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天全站免登陆