UserScript基于按键执行操作?

时间:2012-09-24 03:59:46

标签: javascript javascript-events userscripts onkeydown

我正在努力编写我正在尝试编写的用户脚本的语法,基本上应遵循以下逻辑:

IF (LeftArrowKeyIsPressed) THEN doSomething;
ELSE IF (RightArrowKeyIsPressed) THEN doSomethingElse;
ELSE IF (any other key pressed) THEN doNothing;

有人可以帮我解决构建按键检查的代码语法吗?假设正在使用onkeydown事件。

1 个答案:

答案 0 :(得分:1)

使用addEventListener添加一个事件监听器,可能是在窗口中。然后关闭Event.which值以执行您想要的操作。

这是代码。 See it in action at jsFiddle.

/*--- Get or set the codes for the arrow keys.
    Firefox gives us nice constants, Chrome does not.
*/
KeyEvent        = (typeof KeyEvent === "object")  ?  KeyEvent  :  [];
const LEFT_KEY  = KeyEvent.DOM_VK_LEFT   ||  37;
const RIGHT_KEY = KeyEvent.DOM_VK_RIGHT  ||  39;

window.addEventListener ("keydown", keyboardHandler, false);

function keyboardHandler (zEvent) {
    var bBlockDefaultAction = false;

    //--- Assume we want only the plain keys, not the modified versions.
    if (zEvent.altKey  ||  zEvent.ctrlKey  ||  zEvent.shiftKey) {
        //-- Do nothing (most user-friendly option, in most cases).
    }
    else {
        if (zEvent.which == LEFT_KEY) {
            //DO LEFT KEY ACTION HERE.
            bBlockDefaultAction = true;
        }
        else if (zEvent.which == RIGHT_KEY) {
            //DO RIGHT KEY ACTION HERE.
            bBlockDefaultAction = true;
        }
    }

    if (bBlockDefaultAction) {
        zEvent.preventDefault ();
        zEvent.stopPropagation ();
    }
}

此代码适用于适用于用户脚本的浏览器(非IE)。除了将addEventListener行更改为:

之外,jQuery版本是相同的
$(window).keydown (keyboardHandler);