javascript 使用Javascript检测鼠标点击div没有副作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4631975/
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-10-25 14:22:17  来源:igfitidea点击:

Detecting mouse click on div with Javascript without side-effects

javascripthtml

提问by Imran

I want to detect whenever someone clicks in a div (essentially I want to know when a user is interacting with a section of text on my site, be that by selecting some text or clicking on a link), but I don't want to interfere with what the user is doing.

我想检测何时有人点击 div(本质上我想知道用户何时与我网站上的一段文本进行交互,无论是通过选择一些文本还是单击链接),但我不想干扰用户正在做的事情。

If I put a onmousedown or onclick event on the div it ends up breaking selection, links, etc. Is there any way to catch these events without causing any interference ?

如果我在 div 上放置一个 onmousedown 或 onclick 事件,它最终会破坏选择、链接等。有没有办法在不引起任何干扰的情况下捕获这些事件?

回答by David Tang

Onmousedown or onclick shouldn't interfere with anything as long as it doesn'treturn false;.

Onmousedown 或 onclick 不应该干扰任何东西,只要它return false;

You can do this:

你可以这样做:

document.getElementById("spy-on-me").onmousedown = function () {
    console.log("User moused down");
    return true; // Not needed, as long as you don't return false
};

If you have other scripts that are attaching behaviour via this method on the page, then to prevent overriding them you can do:

如果您有其他脚本通过页面上的此方法附加行为,则为防止覆盖它们,您可以执行以下操作:

var spyElement = document.getElementById("spy-on-me");
var oldMousedown = spyElement.onmousedown;
spyElement.onmousedown = function () {
    console.log("User moused down");
    if(oldMousedown) oldMousedown();
};

回答by Marcus Whybrow

Yes, I suspect you are currently returning falseat the end of the event binding, just don't do that or any of the things in this binding:

是的,我怀疑您目前正在false事件绑定结束时返回,只是不要这样做或此绑定中的任何事情:

$('a').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
});

If you do not do any of these three things, jQuery will not stop the event from bubbling up to the browser.

如果你不做这三件事中的任何一件,jQuery 将不会阻止事件冒泡到浏览器。

Edit:Sorry didn't realise it was a plain JavaScript question.

编辑:抱歉没有意识到这是一个简单的 JavaScript 问题。

回答by e11438

you can use do it by adding a event listener as well

您也可以通过添加事件侦听器来使用它

var myNode= document.querySelector('.imagegrid'); 
myNode.addEventListener("click",function(e){    
 alert(e.target+" clicked"); 
}); 

A similar example is demonstrated here

这里展示一个类似的例子

回答by CZar

Can't you simply add a click event to the div?

你不能简单地向div添加一个点击事件吗?

<div id="secretDiv" (click)="secretDivClick()">

then on your component:

然后在您的组件上:

secretDivClick() {
console.log('clicked');
}