本文介绍了仅每个元素的addEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想让我的画布仅响应按键/鼠标事件监听器。 另一个用户遇到了这个问题: addEventListener用于画布上的按键按下 但问题仍然存在:我有画布和输入框。我有空格键来触发事件,但是当我要在输入元素框中键入内容时,它也会触发。 如何使按键/鼠标事件排他 // js文件 gameCanvas = document.getElementById('gameCanvas'); document.addEventListener( keydown,function(e){ if(e.keyCode == 32)//触发画布},false); // html dom < canvas id = gameCanvas tabindex ='1'>< / canvas> //输入意外触发了上述事件,该事件意味着画布< input type = text id = conversation>< / input> 解决方案您可以为每个创建单独的keydown / click事件您的输入/画布。 要使画布响应按键按下,您需要添加 tabindex = 1 。 就像< canvas id = gameCanvas tabindex = 1>< / canvas> 输入和画布都将在选择正确的元素时响应键盘事件,并在按下键时触发。如果您喜欢单击事件,只需将 keydown 替换为 click 。 // js文件gameCanvas = document.getElementById('gameCanvas');对话= document.getElementById(对话); gameCanvas.addEventListener( keydown,function(e){console.log(gameCanvas);},false); session.addEventListener( keydown,function(e){console.log(conversation);},false); #gameCanvas {背景:蓝色;宽度:100px;高度:100px; } < p> gamecanvas< / p>< canvas id = gameCanvas tabindex = 1>< / canvas>< br />< p>会话< / p> < input id = conversation type = text tabindex = 2>< / input> I want to make my canvas to exclusively respond to keydown/mouse EventListeners only.Another user had this problem: addEventListener for keydown on CanvasBut the problem still persists: I have a canvas and an input box. I have the spacebar to trigger an event but when I want to type in an input element box, it will trigger as well.How do I make keydown/mouse events exclusive for the canvas so it won't affect other elements such as my input? //js file gameCanvas = document.getElementById('gameCanvas'); document.addEventListener("keydown", function(e){ if(e.keyCode == 32) // triggers something in canvas }, false); //html dom <canvas id="gameCanvas" tabindex='1'></canvas> //input that accidentally triggers the above event meant for canvas <input type="text" id="conversation"></input> 解决方案 You can create separate keydown/click event for each of your input/canvas.To get canvas to response to keydown you need to add tabindex="1".Like so <canvas id="gameCanvas" tabindex="1"></canvas>Both input and canvas will response to keyboard event when the right elements are selected and triggered when keys are pressed. If you prefer click event just replace keydown with click instead.//js file gameCanvas = document.getElementById('gameCanvas'); conversation = document.getElementById('conversation'); gameCanvas.addEventListener("keydown", function(e){ console.log(gameCanvas); }, false); conversation.addEventListener("keydown", function(e){ console.log(conversation); }, false);#gameCanvas { background: blue; width: 100px; height: 100px; }<p>gamecanvas</p><canvas id="gameCanvas" tabindex="1"></canvas><br /><p>conversation</p> <input id="conversation" type="text" tabindex="2"></input> 这篇关于仅每个元素的addEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-22 00:21