我正在努力编写我正在尝试编写的用户脚本的语法,基本上应遵循以下逻辑:
IF (LeftArrowKeyIsPressed) THEN doSomething; ELSE IF (RightArrowKeyIsPressed) THEN doSomethingElse; ELSE IF (any other key pressed) THEN doNothing;
有人可以帮我解决构建按键检查的代码语法吗?假设正在使用onkeydown
事件。
答案 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
行更改为:
$(window).keydown (keyboardHandler);