简体   繁体   中英

Listen For Keydown Event On Hovered Element

I would like to detect a control key hit, without losing the user's current focus.

For example (see below) a user is writing something into a textarea, the textarea is the current element focused. Then my end user moves his mouse on a div (just hovered, not clicked), and if he presses a control key I would like to execute a function (the keyDown ones below).

To make it works I had to add a tabIndex to my div , and I had to uncomment the theDiv.focus() line which makes me sad because it causes a loss of focus on my active textarea.

How can I simultaneously detect if someone hits a key when his mouse is on a specific element, without losing the current element's focus?

 var theDiv = document.getElementById("theDiv"); function entered(e) { theDiv.addEventListener("keydown", keyDown); //theDiv.focus(); } function keyDown(e) { alert(e.key) } theDiv.addEventListener("mouseover", entered); 
 #theDiv { width: 100px; height: 100px; border: 1px silver solid; } #theDiv:hover { border: 1px silver dashed; } 
 <div id="theDiv" tabindex="-1"> </div> <div> <textarea id="a">Click here, then hover the div above and hold "Shift" key</textarea> </div> 

You can add mouseover event listener to the document to store the element that is being hovered over in a global variable. When there is a keydown event on the document, prevent the default action if the div if being hovered over (so no text will be printed into the textarea).

 var theDiv = document.getElementById("theDiv"); var hoverTarget = document.body; var res = document.getElementById("result"); document.addEventListener("mouseover", function(e){ hoverTarget = e.target; }); function keyDown(e) { res.innerText = "Key: "+e.key+" KeyCode: "+e.keyCode; } document.addEventListener("keydown", function(e){ if(hoverTarget===theDiv){ e.preventDefault(); keyDown(e); } }); 
 #theDiv { width: 100px; height: 100px; border: 1px silver solid; } #theDiv:hover { border: 1px silver dashed; } 
 <div id="theDiv" tabindex="-1"> </div> <div> <textarea id="a">Click here, then hover the div above and hold "Shift" key</textarea> </div> <span id="result"> </span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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