Html Javascript检测div之外的点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18893144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:34:47  来源:igfitidea点击:

Javascript Detect click event outside of div

javascripthtmleventsclick

提问by Dibish

I have a div with id="content-area", when a user clicks outside of this div, I would like to alert them to the fact that they clicked outside of it. How would I use JavaScript to solve this issue?

我有一个 id="content-area" 的 div,当用户在这个 div 之外点击时,我想提醒他们他们点击了它之外的事实。我将如何使用 JavaScript 来解决这个问题?

<div id = "outer-container">
   <div id = "content-area">
      Display Conents 
   </div>
</div>

回答by jollelj

In pure Javascript

在纯 Javascript 中

Check out this fiddle and see if that's what you're after!

看看这个小提琴,看看这是否是你所追求的!

document.getElementById('outer-container').onclick = function(e) {
    if(e.target != document.getElementById('content-area')) {
        document.getElementById('content-area').innerHTML = 'You clicked outside.';          
    } else {
        document.getElementById('content-area').innerHTML = 'Display Contents';   
    }
}

http://jsfiddle.net/DUhP6/2/

http://jsfiddle.net/DUhP6/2/

回答by Butt4cak3

Bind the onClick-Event to an element that is outside your content area, e.g. the body. Then, inside the event, check whether the target is the content area or a direct or indirect child of the content area. If not, then alert.

将 onClick-Event 绑定到内容区域之外的元素,例如正文。然后,在事件内部,检查目标是内容区域还是内容区域的直接或间接子级。如果没有,则报警。

I made a function that checks whether it's a child or not. It returns true if the parent of a node is the searched parent. If not, then it checks whether it actually has a parent. If not, then it returns false. If it has a parent, but it's not the searched one, that it checks whether the parent's parent is the searched parent.

我做了一个函数来检查它是否是一个孩子。如果节点的父节点是搜索到的父节点,则返回 true。如果没有,那么它会检查它是否真的有一个父节点。如果不是,则返回false。如果它有一个父级,但不是搜索到的,则检查父级的父级是否是搜索到的父级。

function isChildOf(child, parent) {
    if (child.parentNode === parent) {
      return true;
    } else if (child.parentNode === null) {
      return false;
    } else {
      return isChildOf(child.parentNode, parent);
    }
}

Also check out the Live Example(content-area = gray)!

另请查看实时示例(内容区域 = 灰色)!

回答by Jan Vorcak

The Node.contains()method returns a Boolean value indicating whether a node is a descendant of a given node or not

所述Node.contains()方法返回一个布尔值,表示节点是否是一个给定的节点的后代或不

You can catch events using

您可以使用捕获事件

document.addEventListener("click", clickOutside, false);
function clickOutside(e) {
   const inside = document.getElementById('content-area').contains(e.target);
}

Remember to remove the event listened in the right place

记得删除在正确位置监听的事件

document.removeEventListener("click", clickOutside, false)

回答by Joe Thomas

I made a simple and small js libraryto do this for you:

我做了一个简单而小的js库来为你做这件事:

It hiHymans the native addEventListener, to create a outclick event and also has a setter on the prototype for .onoutclick

它劫持了本机 addEventListener,以创建一个 outclick 事件,并且还在 .onoutclick 的原型上有一个 setter

Basic Usage

Using outclick you can register event listeners on DOM elements to detect whether another element that was that element or another element inside it was clicked. The most common use of this is in menus.

var menu = document.getElementById('menu')

menu.onoutclick = function () {
    hide(menu)
}

this can also be done using the addEventListener method

var menu = document.getElementById('menu')

menu.addEventListener('outclick', function (e) {
    hide(menu)
})

Alternatively, you can also use the html attribute outclick to trigger an event. This does not handle dynamic HTML, and we have no plans to add that, yet

<div outclick="someFunc()"></div>

基本用法

使用 outclick 可以在 DOM 元素上注册事件侦听器,以检测是否单击了该元素的另一个元素或其中的另一个元素。最常见的用途是在菜单中。

var menu = document.getElementById('menu')

menu.onoutclick = function () {
    hide(menu)
}

这也可以使用 addEventListener 方法完成

var menu = document.getElementById('menu')

menu.addEventListener('outclick', function (e) {
    hide(menu)
})

或者,您也可以使用 html 属性 outclick 来触发事件。这不处理动态 HTML,我们还没有计划添加它,但

<div outclick="someFunc()"></div>

Have fun!

玩得开心!

回答by FidEliO

Use document.activeElementto see which of your html elements is active.

使用document.activeElement看,你的HTML元素的激活。

Here is a reference: document.activeElement in MDN

这里有一个参考: MDN 中的 document.activeElement

回答by TomNg

$('#outer-container').on('click', function (e) {
     if (e.target === this) {
        alert('clicked outside');
     }
});

This is for the case that you click inside the outer-containerbut outside of the content-area.

这是针对您在external-container内部但在content-area外部单击的情况。

回答by BENARD Patrick

Here is the fiddle : http://jsfiddle.net/uQAMm/1/

这是小提琴:http: //jsfiddle.net/uQAMm/1/

$('#outercontainer:not(#contentarea)').on('click', function(event){df(event)} );
function df(evenement)
{
    var xstart = $('#contentarea').offset().left;
    var xend = $('#contentarea').offset().left + $('#contentarea').width();

    var ystart = $('#contentarea').offset().top;
    var yend = $('#contentarea').offset().top + $('#contentarea').height(); 

    var xx = evenement.clientX;
    var yy = evenement.clientY;

    if ( !(  ( xx >=  xstart && xx <=  xend ) && ( yy >=  ystart && yy <=  yend )) )
    {
        alert('out');
    }


}

回答by Simon Rigét

Put this into your document:

将其放入您的文档中:

<script>
document.onclick = function(e) {
  if(e.target.id != 'content-area') alert('you clicked outside of content area');
}
</script>

回答by Ronak Patel

use jquery as its best for DOM access

使用 jquery 作为 DOM 访问的最佳选择

$(document).click(function(e){
 if($(e.target).is("#content-area") || $(e.target).closest("#content-area").length)
  alert("inside content area");
else alert("you clicked out side content area");
});