检测点击外部元素(vanilla JavaScript) [英] Detect click outside element (vanilla JavaScript)

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

问题描述

我到处搜索了一个很好的解决方案,但是找不到不使用jQuery 的解决方案。



是否有跨浏览器,正常方式(没有奇怪的黑客或容易破解代码),检测元素外部的点击(可能有孩子也可能没有孩子)?

解决方案

将事件监听器添加到 document 并使用 Node.contains() 查找事件的目标(即最内部点击的元素)在指定的元素内。它甚至可以在IE5中运行

  var specifiedElement = document.getElementById('a'); 

//我正在使用点击但它适用于任何事件
document.addEventListener('click',function(event){
var isClickInside = specifiedElement.contains (event.target);

if(!isClickInside){
//点击在指定元素之外,做点什么
}
});

  var specifiedElement = document.getElementById('a'); //我正在使用click但它适用于任何eventdocument.addEventListener('click',function(event){var isClickInside = specifiedElement.contains( event.target); if(isClickInside){alert('你点击A')} else {alert('你点击A')}}};  

< pre class =snippet-code-css lang-css prettyprint-override> div {margin:auto;填充:1em;最大宽度:6em; background:rgba(0,0,0,.2); text-align:center;}

 点击A内或者在外面?< div id =a> A< div id =b> B< div id =c> C< / div> < / div>< / div>  


I have searched for a good solution everywhere, yet I can't find one which does not use jQuery.

Is there a cross-browser, normal way (without weird hacks or easy to break code), to detect a click outside of an element (which may or may not have children)?

解决方案

Add an event listener to document and use Node.contains() to find whether the target of the event (which is the inner-most clicked element) is inside your specified element. It works even in IE5

var specifiedElement = document.getElementById('a');

//I'm using "click" but it works with any event
document.addEventListener('click', function(event) {
  var isClickInside = specifiedElement.contains(event.target);

  if (!isClickInside) {
    //the click was outside the specifiedElement, do something
  }
});

var specifiedElement = document.getElementById('a');

//I'm using "click" but it works with any event
document.addEventListener('click', function(event) {
  var isClickInside = specifiedElement.contains(event.target);
  if (isClickInside) {
    alert('You clicked inside A')
  } else {
    alert('You clicked outside A')
  }
});

div {
  margin: auto;
  padding: 1em;
  max-width: 6em;
  background: rgba(0, 0, 0, .2);
  text-align: center;
}

Is the click inside A or outside?
<div id="a">A
  <div id="b">B
    <div id="c">C</div>
  </div>
</div>

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

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