简体   繁体   English

结合鼠标单击并在同一事件侦听器中输入按键

[英]Combining mouse click and enter key press in the same event listener

I have a div that I made focusable with tabindex, and I want it to act like a button, doing something on both mouse click and enter key press. 我有一个div,可以通过tabindex使其聚焦,并且我希望它像按钮一样,在单击鼠标和输入键时都做一些事情。 Can you do this with a single event listener, combining the following into one? 您可以使用单个事件侦听器将以下内容组合为一个吗?

document.getElementById("myId").addEventListener("click", function() {
    console.log("click");
});
document.getElementById("myId").addEventListener("keyup", function(e) {
    if(e.keyCode === 13) {
        console.log("click");
    }
});

You can put the events to handle in an Array and use forEach to add the event listener to the element. 您可以将events放在Array中处理,并使用forEach将事件侦听器添加到元素。

 <div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div> <script> var div = document.querySelector('div'); ["click", "keypress"].forEach(ev=>{ div.addEventListener(ev, function(e){ if(ev=="click"){ console.log("click");//clicked } if(e.keyCode==13){ console.log("click");//enter key pressed } }); }); </script> 

You can also define a function that both of the event listeners call. 您还可以定义两个事件侦听器都调用的函数。

 <div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div> <script> var div = document.querySelector('div'); ["click", "keypress"].forEach(ev=>{ div.addEventListener(ev, handleEvent); }); function handleEvent(e){ if(e.type=="click"){ console.log("click");//clicked } if(e.keyCode==13){ console.log("click");//enter key pressed } } </script> 

No, you need to use two listeners, but as you have to pass a function to the listener which is called and gets all the necessary arguments you can create a single function for both cases like this: 不,您需要使用两个侦听器,但是由于您必须将一个函数传递给被调用的侦听器并获取所有必要的参数,因此您可以为两种情况创建一个函数,如下所示:

function handleEvent(e){
   if(e //make sure a mouseEvent has been passed as argument
       &&
      e.keyCode === 13 //check for the correct key
   ){
      console.log("click");
   }
}

document.getElementById("myId").addEventListener("click", handleEvent);
document.getElementById("myId").addEventListener("keyup", handleEvent);

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

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