使用javascript检测div外部点击 [英] Detect click outside div using javascript

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

问题描述

我想检测div区域内部或外部的点击.棘手的部分是div将包含其他元素,并且如果单击div内部的元素之一,则应将其视为内部单击,就像单击div外部的元素一样,也应将其视为外部点击.

I'd like to detect a click inside or outside a div area. The tricky part is that the div will contain other elements and if one of the elements inside the div is clicked, it should be considered a click inside, the same way if an element from outside the div is clicked, it should be considered an outside click.

我已经进行了很多研究,但我能找到的只是jquery中的示例,我需要纯JavaScript.

I've been researching a lot but all I could find were examples in jquery and I need pure javascript.

任何建议将不胜感激.

推荐答案

这取决于各个用例,但听起来在此示例中,主div中可能还有其他嵌套元素,例如更多div,列表等.使用 Node.contains 是检查目标元素是否在要检查的div内的有用方法.

It depends on the individual use case but it sounds like in this example there are likely to be other nested elements inside the main div e.g. more divs, lists etc. Using Node.contains would be a useful way to check whether the target element is within the div that is being checked.

window.addEventListener('click', function(e){   
  if (document.getElementById('clickbox').contains(e.target)){
    // Clicked in box
  } else{
    // Clicked outside the box
  }
});

在内部具有嵌套列表的示例是此处.

An example that has a nested list inside is here.

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

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