gpt4 book ai didi

javascript - 右键单击停止传播

转载 作者:行者123 更新时间:2023-11-29 22:09:46 25 4
gpt4 key购买 nike

如何停止 javascript 中右键单击事件的传播,使父元素根本检测不到它们?当我单击以下 html 中的链接时,未检测到左键单击,但文档元素将右键单击检测为“单击”事件而不是“上下文菜单”事件。我尝试将事件监听器附加到 mousedown、contextmenu,但没有成功。

[编辑] 将代码更改为 contextmenu 适用于 chrome 但不适用于 firefox (v23.0.1),这可能是 firefox 的错误。

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="application/javascript;version=1.8">

function log(s){
document.getElementById('log').innerHTML+=s+'<br/>';
}

window.onload=function(){
document.addEventListener('click',function(e){
log('click detected');
},false);

let link=document.querySelector('a#link');
//click only cares about left clicks
link.addEventListener('click',function(e){
e.stopPropagation();
return false;
},false);
};

</script>
</head>

<body>

<a id="link" href="javascript:void(0);">Link</a>

<div id="log"></div>

</body>
</html>

最佳答案

“右键单击”事件称为“上下文菜单”事件。

http://www.quirksmode.org/dom/events/contextmenu.html


例子:

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>

function log(s){
document.getElementById('log').innerHTML+=s+'<br/>';
}

window.onload=function(){
document.addEventListener('click',function(e){
log('click detected');
},false);

document.addEventListener('contextmenu', function(e){
log('right-click detected');
}, false);

var link=document.querySelector('a#link');

link.addEventListener('click',function(e){
e.stopPropagation();
return false;
},false);

link.addEventListener('contextmenu',function(e){
e.stopPropagation();
return false;
},false);
};

</script>
</head>

<body>

<a id="link" href="javascript:void(0);">Link</a>

<div id="log"></div>

</body>
</html>

关于javascript - 右键单击停止传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18676412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com