简体   繁体   English

如何捕捉浏览器外的点击 - Javascript

[英]How can I catch the click outside the browser - Javascript

For my project, I need to catch all the click outside the browser in Javascript.对于我的项目,我需要在 Javascript 中捕获浏览器外的所有点击。 Is there a way to do that ?有没有办法做到这一点 ? For example by asking the user the right access ?例如通过询问用户正确的访问权限? I need a function like "onclick" that works even outside the browser.我需要一个像“onclick”这样的功能,它甚至可以在浏览器之外工作。

There are various approaches for detecting when the focus moves out of the current page which would be a side effect of clicking outside the window if the window currently has focus.有多种方法可以检测焦点何时移出当前页面,如果窗口当前具有焦点,这将是在窗口外单击的副作用。

Explicitly detecting clicks outside the page is not possible.无法显式检测页面外的点击。 It would be a security problem if a web page could monitor how the user interacts with other applications.如果网页可以监控用户如何与其他应用程序交互,那将是一个安全问题。

To detect click outside element with JavaScript, we can use the element's contains method.要使用 JavaScript 检测点击外部元素,我们可以使用元素的 contains 方法。

For instance, we write例如,我们写

const specifiedElement = document.getElementById("a");

document.addEventListener("click", (event) => {
  const isClickInside = specifiedElement.contains(event.target);

  if (!isClickInside) {
    // ...
  }
});

to select the element we want to check with getElemebntById.选择我们要使用 getElemebntById 检查的元素。

Then we add a click listener for the whole page with document.addEventListener.然后我们用 document.addEventListener 为整个页面添加一个点击监听器。

In the callback, we call specifiedElement.contains with event.target to check if we clicked inside the a element.在回调中,我们使用 event.target 调用 specifiedElement.contains 来检查我们是否在 a 元素内单击。

If it's false, then we clicked outside of it.如果它是假的,那么我们点击它之外。

javascript detect click outside of element javascript检测元素外的点击

var ignoreClickOnMeElement = document.getElementById('someElementID');

document.addEventListener('click', function(event) {
    var isClickInsideElement = ignoreClickOnMeElement.contains(event.target);
    if (!isClickInsideElement) {
        //Do something click is outside specified element
    }
});

click outside javascript点击外部 javascript

// Vanilla js
var ignoreMe = document.getElementById("ignoreMe");
window.addEventListener('mouseup', function(event){
    if (event.target != ignoreMe && event.target.parentNode != ignoreMe){
    // Place your output
    }
});

https://www.codegrepper.com/code-examples/javascript/javascript+detect+click+outside+of+element https://www.codegrepper.com/code-examples/javascript/javascript+detect+click+outside+of+element

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM