检测用户何时在div之外单击 [英] Detecting when a user clicks outside a div

查看:93
本文介绍了检测用户何时在div之外单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向用户显示模式/灯箱.当用户单击按钮时,模态显示出来,页面的其余部分变暗.常用的东西.

I'm showing the user a modal/lightbox. The modal shows up and the rest of the page goes dim when the user clicks a button. Usual stuff.

但是我想这样做.如果用户单击模态之外的任何元素,我希望模态消失,页面返回正常状态.

However I want to do this. If the user clicks any element outside of the modal, I want the modal to go away and the page to return to normal.

这怎么办?我知道我可以为主体设置一个onclick事件,然后检查事件目标是否是我的模态,但是如果用户单击模态内的链接/文本框/按钮该怎么办?在这种情况下,目标将不会是模态.我该如何解决?

How can this be done? I know I can set an onclick event for body, and then check if event target is my modal, but what if the user clicks on a link/textbox/button within the modal? In that case, target won't be the modal. How can I solve this?

有没有一种方法可以检查事件目标是否包含在<div id="modal"></div>中,所以如果存在,我就不会关闭模式,如果没有,则意味着用户单击了模式之外的我就可以将其关闭?

Is there a way to check if the event target is contained with <div id="modal"></div>, so if it is, I won't close the modal, and if not, that means user clicked outside the modal and I can close it?

推荐答案

您可以将div放在填充整个空间的模式下,并在其上附加点击处理程序.

You could put a div under the modal that fills the entire space and attach your click handler to it.

这篇关于检测用户何时在div之外单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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