[英]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). 然后,我的最终用户将鼠标移到div上(只是悬停,没有单击),如果他按下控制键,我想执行一个功能(下面的keyDown
)。
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. 为了使其正常工作,我必须在div
添加一个tabIndex
,并且必须取消对theDiv.focus()
行的注释,这使我很难过,因为这会导致我对活动文本区域失去关注。
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. 您可以将mouseover
事件侦听器添加到文档中,以将要悬停的元素存储在全局变量中。 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). 当文档上发生keydown
事件时,如果将div
悬停在div
上,则阻止默认操作(这样就不会在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.