直到窗口被点击,keydown才被检测到 [英] keydown not detected until window is clicked
问题描述
在我的web应用程序中,我有一个用于打开菜单的键的事件监听器。这仅仅在我点击了页面上的任何地方后才起作用。我已经尝试添加焦点到窗口onload ...但是这仍然不让keydown函数运行,直到我已经点击页面上的某个地方。
有没有人知道这是可能的吗?我无法想象,它不是,但 .focus();
不是我所尝试的goto
我的主要功能的示例:
$ p $ document.addEventListener('DOMContentLoaded',function(){
();
document.addEventListener('keydown',function(event){
var key = event.keyCode;
if(key == 36){
toggleMenu();
event.preventDefault();
}
});
});
检查这个小提琴:小提琴
使用 $(窗口)。焦点();
(用jquery)
编辑:
这里是本地javascript的解决方案: 小提琴
首先check_focus()函数如果文档没有焦点,然后检测到按键,则关注窗口。
希望这有助于。
In my web application I have an event listener for a key that opens a menu. This works just fine only AFTER I have clicked anywhere on the page. I have tried to add focus to the window onload...but this still does not let the keydown function run until after I have clicked somewhere on the page.
Does anyone know if this is possible? I can't imagine that it is not, but .focus();
is not the goto as far as I have tried
Example of my primary function:
document.addEventListener('DOMContentLoaded', function() {
// I have tried window.focus(); and window.document.focus();
document.addEventListener('keydown', function(event) {
var key = event.keyCode;
if (key == 36) {
toggleMenu();
event.preventDefault();
}
});
});
Check this fiddle here : fiddle
Use $(window).focus();
(with jquery)
EDIT : Here's the solution in native javascript : fiddle
First the check_focus() function focuses on the window if the document doesnt have focus and then detects a keypress.
Hope this helps.
这篇关于直到窗口被点击,keydown才被检测到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!