简体   繁体   English

防止 mousedown 的点击事件

[英]Prevent click event from mousedown

I tried the following code on Chrome, Firefox and IE:我在 Chrome、Firefox 和 IE 上尝试了以下代码:

var test = document.getElementById('test');

test.addEventListener( 'click', function ( e ) {
  alert( 'clicked' );
});

test.addEventListener( 'mousedown', function ( e ) {
  e.stopImmediatePropagation();
  e.stopPropagation();
});

In chrome, the alert will not be fired;在 chrome 中,不会触发警报; in firefox and ie, yes.在 firefox 中,即,是的。 Which is the correct behaviour?哪个是正确的行为? How can I prevent the click event to be fired?如何防止点击事件被触发?

jsBin Example jsBin 示例

If you want to cancel the click event, you can do that in the Capture phase.如果你想取消点击事件,你可以在 Capture 阶段进行。 Attach a click listener to the body to cancel the click event on the required element.将单击侦听器附加到正文以取消所需元素上的单击事件。 The third argument in addEventListener lets you specify if you want to use the capture phase. addEventListener 中的第三个参数允许您指定是否要使用捕获阶段。

http://jsbin.com/kocapuharo/1/edit?html,css,js,output http://jsbin.com/kocapuharo/1/edit?html,css,js,output

There you go. Just run the snippet.你是 go。只需运行该代码段即可。

 const element = document.getElementById('test'); setupElement(element); function setupElement(element){ let clickedByMouse = false; element.onclick = (e) => { console.log(clickedByMouse); if(clickedByMouse){ e.preventDefault(); }else{ doSomething(); clickedByMouse = false;//reset clickByMouse if needed } console.log(clickedByMouse); } element.onmousedown = (e) => { clickedByMouse = true; } }
 #test { height: 200px; background-color: #000; }
 <div id="test"></div>

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

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