在单击 window 之前未检测到 keydown
keydown not detected until window is clicked
在我的 Web 应用程序中,我有一个用于打开菜单的键的事件侦听器。只有在我单击页面上的任意位置后,这才可以正常工作。我试图将焦点添加到 window onload...但这仍然不会让 keydown 功能 运行 直到我点击页面上的某个地方。
有人知道这是否可行吗?我无法想象它不是,但 .focus();
不是我尝试过的 goto
我的主要功能示例:
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();
}
});
});
希望这会有所帮助:
http://jsfiddle.net/yL67u5th/1/
$('#adaw').keydown(function (e) {
var o = {
45: 'INSERT',
46: 'DELETE'
};
console.log(e.ctrlKey, e.shiftKey, e.which, o[e.which]);
$('<div/>', {
text: (e.ctrlKey ? 'CTRL and ' : '') + (e.shiftKey ? 'SHIFT and ' : '') + (o[e.which] ? o[e.which] : '') + ' was pressed!'
}).appendTo('#adaw');
});
$('#adaw').focus();
在此处检查 fiddle:fiddle
使用$(window).focus();
(使用jquery)
编辑:
这是本机 javascript 中的解决方案:fiddle
如果文档没有焦点,check_focus() 函数首先关注 window,然后检测按键。
希望对您有所帮助。
在我的 Web 应用程序中,我有一个用于打开菜单的键的事件侦听器。只有在我单击页面上的任意位置后,这才可以正常工作。我试图将焦点添加到 window onload...但这仍然不会让 keydown 功能 运行 直到我点击页面上的某个地方。
有人知道这是否可行吗?我无法想象它不是,但 .focus();
不是我尝试过的 goto
我的主要功能示例:
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();
}
});
});
希望这会有所帮助:
http://jsfiddle.net/yL67u5th/1/
$('#adaw').keydown(function (e) {
var o = {
45: 'INSERT',
46: 'DELETE'
};
console.log(e.ctrlKey, e.shiftKey, e.which, o[e.which]);
$('<div/>', {
text: (e.ctrlKey ? 'CTRL and ' : '') + (e.shiftKey ? 'SHIFT and ' : '') + (o[e.which] ? o[e.which] : '') + ' was pressed!'
}).appendTo('#adaw');
});
$('#adaw').focus();
在此处检查 fiddle:fiddle
使用$(window).focus();
(使用jquery)
编辑: 这是本机 javascript 中的解决方案:fiddle
如果文档没有焦点,check_focus() 函数首先关注 window,然后检测按键。
希望对您有所帮助。