简体   繁体   中英

Is it possible to listen for keydown and keyup while resizing window

I'm trying to detect keydown and keyup , while the window is being resized. What I've tried so far, only fires the key events after the resize is finished.

$(window).resize(function(){
    console.log("resizing");    
});

$(window).keydown(function(e){
    $("#key").css("background","green");
});

$(window).keyup(function(e){
    $("#key").css("background","red");
});

Okay, so part of the problem you may be running into here is that keydown isn't an on or off thing, it's a fire-constantly thing.
The same is true of onresize .

As you resize the window the event gets called over and over.
Also, because JS isn't multithreaded, only one of these events is going to happen at one time. The other event is going to be queued up to run immediately after the other event finishes.

So what you actually want is a state machine that one event sets, and the other event checks.

Quick examples:

var BrowserWindow = { width : 0, height : 0, prevWidth : 0, prevHeight : 0 };

window.onresize = function (e) {
   /* set prevWidth/prevHeight, get new width/height */
};

window.onkeydown = function (e) {
    if (BrowserWindow.prevWidth !== BrowserWindow.width) { /*...*/ }
};

That would work (except that it would only work when the screen was actively being stretched... so it wouldn't happen in the case where the key was down and the edge of the window was being held but not dragged (which might lead to flickering if the browser fires keydown events more-frequently than resize).

The more appropriate answer would likely be to go the other way:

var Keyboard = {
    currentKeys : {},
    previousKeys : {}
};


window.onkeydown = function (e) { Keyboard.currentKeys[e.keyCode] = true; };
window.onkeyup   = function (e) { delete Keyboard.currentKeys[e.keyCode]; };


window.onresize = function (e) {
    var key = <X>,
        state = "";

    state = Keyboard.currentKeys[key] && !Keyboard.previousKeys[key]
          ?    "pressed"
          : !Keyboard.currentKeys[key] && Keyboard.previousKeys[key]
          ?    "released"
          : Keyboard.currentKeys[key] && Keyboard.previousKeys[key]
          ?    "held"
          :    "off";

    Keyboard.previousKeys = Keyboard.currentKeys;
    doSomething(state);
};

This is less than perfect from an architecture standpoint, but is more along the idea of what you'd have to do in another environment.

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