使用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();
}
}
此代碼的工作就userscripts適用的瀏覽器(IE沒有)。 jQuery的版本是,除了改變addEventListener
線相同的:
$(window).keydown (keyboardHandler);
謝謝,夥計,我一直在掙扎了,如果系統的結構,所以這是非常有用的。這應該被標記爲用戶指南,國際海事組織:) –
不客氣;樂意效勞。 –