-->

keydown not detected until window is clicked

2019-07-09 00:09发布

问题:

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();
            }
        });
    });

回答1:

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.



回答2:

Hope this will help :

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();