71

这是我的代码:

function pauseSound() {
    var pauseSound = document.getElementById("backgroundMusic");
    pauseSound.pause(); 
}

我想为这段代码添加一个键盘快捷键,我该怎么做才能在单击按钮时也执行该功能?

试图添加一个 else if 语句,但它不起作用,有什么想法吗?

function doc_keyUp(e) {
    if (e.ctrlKey && e.keyCode == 88) {
        pauseSound();
    }

    else if (e.ctrlKey && e.keyCode == 84) {
        playSound();
    }
}
4

10 回答 10

112

文档的 keyup 事件的事件处理程序似乎是一个合适的解决方案。

注意:KeyboardEvent.keyCode已弃用,取而代之的是key.

// define a handler
function doc_keyUp(e) {

    // this would test for whichever key is 40 (down arrow) and the ctrl key at the same time
    if (e.ctrlKey && e.key === 'ArrowDown') {
        // call your function to do the thing
        pauseSound();
    }
}
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);
于 2010-03-24T21:16:44.040 回答
10

如果要在按键后触发事件,请尝试:

在本例中按ALT+ a

document.onkeyup=functione{
  var e = e || window.event; // for IE to cover IEs window event-object
  if(e.altKey && e.which == 65) {
    alert('Keyboard shortcut working!');
    return false;
  }
}

这是一个小提琴:https ://jsfiddle.net/dmtf6n27/38/

另请注意,无论您使用的是onkeypress还是,键码编号都存在差异onkeyupW3 Schools 的“KeyboardEvent keyCode”属性有更多信息。

于 2016-02-20T15:40:49.997 回答
6
//For single key: Short cut key for 'Z'
document.onkeypress = function (e) {
    var evt = window.event || e;
    switch (evt.keyCode) {
        case 90:  
            // Call your method Here
            break;
    }
}

//For combine keys like Alt+P
document.onkeyup = function (e) {
    var evt = window.event || e;   
        if (evt.keyCode == 80 && evt.altKey) {
            // Call Your method here   
        }
    }
}
    //ensure if short cut keys are case sensitive.
    //    If its not case sensitive then
    //check with the evt.keyCode values for both upper case and lower case. ......
于 2018-02-12T12:22:35.870 回答
4

这是我的解决方案:

HTMLElement.prototype.onshortcut = function(shortcut, handler) {
    var currentKeys = []
    
    function reset() {
        currentKeys = []
    }

    function shortcutMatches() {
        currentKeys.sort()
        shortcut.sort()

        return (
            JSON.stringify(currentKeys) ==
            JSON.stringify(shortcut)
        )
    }

    this.onkeydown = function(ev) {
        currentKeys.push(ev.key)

        if (shortcutMatches()) {
            ev.preventDefault()
            reset()
            handler(this)
        }

    }

    this.onkeyup = reset
}


document.body.onshortcut(["Control", "Shift", "P"], el => {
    alert("Hello!")
})
  • currentKeys当你调用我的函数时,它会创建一个名为;的数组。这些是那一刻将被按住的键。
  • 每次按下一个键时,由于 感测onkeydown,它被添加到currentKeys数组中。
  • 当按键被释放时,由于 感测到onkeyup,阵列被重置,这意味着此时没有按键被按下。
  • 每次它都会检查快捷方式是否匹配。如果确实如此,它将调用处理程序。
于 2021-03-07T16:00:15.847 回答
3

这对我有用

document.onkeyup=function(e){
  var e = e || window.event;
  if(e.which == 37) {
    $("#prev").click()
  }else if(e.which == 39){
    $("#next").click()
  }
}
于 2017-07-08T11:13:03.453 回答
1

抓住关键代码,然后调用你的函数。此示例捕获ESC键并调用您的函数:

function getKey(key) {
    if ( key == null ) {
        keycode = event.keyCode;
    // To Mozilla
    } else {
        keycode = key.keyCode;
    }
    // Return the key in lower case form    
    if (keycode ==27){
        //alert(keycode);
        pauseSound();
        return false;
    }
    //return String.fromCharCode(keycode).toLowerCase();
}
$(document).ready( function (){
    $(document).keydown(function (eventObj){
        //alert("Keydown: The key is: "+getKey(eventObj));
        getKey(eventObj);
    });
});

对于此示例,您将需要JQUERY 。

于 2010-03-24T21:17:27.567 回答
1

如果你愿意,这里有一些东西可以使用。您可以使用它注册一堆键和处理程序。

注释在代码中,但简而言之,它在 上设置了一个侦听器,document并使用您要侦听的组合键管理散列。

  • 当您注册要侦听的键(组合)时,您提交键码(最好是从导出的“键”属性中获取的常量,您可以为自己添加更多常量),处理程序函数和可能的选项哈希,其中您说Ctrl和/或Alt键是否参与您对该键的计划。
  • 当您取消注册密钥(组合)时,您只需提交密钥和Ctrl/ Alt-ness 的可选哈希。
window.npup = (function keypressListener() {
    // Object to hold keyCode/handler mappings
    var mappings = {};
    // Default options for additional meta keys
    var defaultOptions = {ctrl:false, alt:false};
    // Flag for if we're running checks or not
    var active = false;
    
    // The function that gets called on keyup.
    // Tries to find a handler to execute
    function driver(event) {
        var keyCode = event.keyCode, ctrl = !!event.ctrlKey, alt = !!event.altKey;
        var key = buildKey(keyCode, ctrl, alt);
        var handler = mappings[key];
        if (handler) {handler(event);}
    }
    
    // Take the three props and make a string to use as key in the hash
    function buildKey(keyCode, ctrl, alt) {return (keyCode+'_'+ctrl+'_'+alt);}
    
    function listen(keyCode, handler, options) {
        // Build default options if there are none submitted
        options = options || defaultOptions;
        if (typeof handler!=='function') {throw new Error('Submit a handler for keyCode #'+keyCode+'(ctrl:'+!!options.ctrl+', alt:'+options.alt+')');}
        // Build a key and map handler for the key combination
        var key = buildKey(keyCode, !!options.ctrl, !!options.alt);
        mappings[key] = handler;
    }
    
    function unListen(keyCode, options) {
        // Build default options if there are none submitted
        options = options || defaultOptions;
        // Build a key and map handler for the key combination
        var key = buildKey(keyCode, !!options.ctrl, !!options.alt);
        // Delete what was found
        delete mappings[key];
    }
    
    // Rudimentary attempt att cross-browser-ness
    var xb = {
        addEventListener: function (element, eventName, handler) {
            if (element.attachEvent) {element.attachEvent('on'+eventName, handler);}
            else {element.addEventListener(eventName, handler, false);}
        }
        , removeEventListener: function (element, eventName, handler) {
            if (element.attachEvent) {element.detachEvent('on'+eventName, handler);}
            else {element.removeEventListener(eventName, handler, false);}
        }
    };
    
    function setActive(activate) {
        activate = (typeof activate==='undefined' || !!activate); // true is default
        if (activate===active) {return;} // already in the desired state, do nothing
        var addOrRemove = activate ? 'addEventListener' : 'removeEventListener';
        xb[addOrRemove](document, 'keyup', driver);
        active = activate;
    }
    
    // Activate on load
    setActive();
    
    // export API
    return {
        // Add/replace handler for a keycode.
        // Submit keycode, handler function and an optional hash with booleans for properties 'ctrl' and 'alt'
        listen: listen
        // Remove handler for a keycode
        // Submit keycode and an optional hash with booleans for properties 'ctrl' and 'alt'
        , unListen: unListen
        // Turn on or off the whole thing.
        // Submit a boolean. No arg means true
        , setActive: setActive
        // Keycode constants, fill in your own here
        , key : {
            VK_F1 : 112
            , VK_F2: 113
            , VK_A: 65
            , VK_B: 66
            , VK_C: 67
        }
    };
})();
  
// Small demo of listen and unListen
// Usage:
//   listen(key, handler [,options])
//   unListen(key, [,options])
npup.listen(npup.key.VK_F1, function (event) {
    console.log('F1, adding listener on \'B\'');
    npup.listen(npup.key.VK_B, function (event) {
        console.log('B');
    });
});
npup.listen(npup.key.VK_F2, function (event) {
    console.log('F2, removing listener on \'B\'');
    npup.unListen(npup.key.VK_B);
});
npup.listen(npup.key.VK_A, function (event) {
    console.log('ctrl-A');
}, {ctrl: true});
npup.listen(npup.key.VK_A, function (event) {
    console.log('ctrl-alt-A');
}, {ctrl: true, alt: true});
npup.listen(npup.key.VK_C, function (event) {
    console.log('ctrl-alt-C => It all ends!');
    npup.setActive(false);
}, {ctrl: true, alt: true});

它没有经过严格测试,但似乎工作正常。

Javascript Char Codes (Key Codes)发现很多keyCodes可以使用,

于 2010-03-25T00:08:53.230 回答
1

这些似乎都在使用 deprecatedkeyCodewhich属性。这是一个使用 jQuery 连接事件的非弃用版本:

$("body").on("keyup", function (e) {
    if(e.ctrlKey && e.key == 'x')
        pauseSound();
    else if(e.ctrlKey && e.key == 't')
        playSound();
})

注意:Ctrl+t可能已经分配给打开一个新的浏览器选项卡。

于 2018-05-30T21:36:12.847 回答
0

解决方案:

var activeKeys = [];

//determine operating system
var os = false;
window.addEventListener('load', function() {
  var userAgent = navigator.appVersion;
  if (userAgent.indexOf("Win") != -1) os = "windows";
  if (userAgent.indexOf("Mac") != -1) os = "osx";
  if (userAgent.indexOf("X11") != -1) os = "unix";
  if (userAgent.indexOf("Linux") != -1) os = "linux";
});

window.addEventListener('keydown', function(e) {
  if (activeKeys.indexOf(e.which) == -1) {
    activeKeys.push(e.which);
  }

  if (os == 'osx') {

  } else {
    //use indexOf function to check for keys being pressed IE
    if (activeKeys.indexOf(17) != -1 && activeKeys.indexOf(86) != -1) {
      console.log('you are trying to paste with control+v keys');
    }
    /*
      the control and v keys (for paste)
      if(activeKeys.indexOf(17) != -1 && activeKeys.indexOf(86) != -1){
        command and v keys are being pressed
      }
    */
  }
});

window.addEventListener('keyup', function(e) {
  var result = activeKeys.indexOf(e.which);
  if (result != -1) {
    activeKeys.splice(result, 1);
  }
});

说明:我遇到了同样的问题并想出了自己的解决方案。e.metaKey似乎不适用于 Chrome 和 Safari 中的 keyup 事件。但是,我不确定它是否特定于我的应用程序,因为我有其他算法阻止了一些关键事件,并且我可能错误地阻止了元密钥。

该算法监视按下的键,然后将它们添加到当前正在按下的键列表中。释放后,该键将从列表中删除。通过使用indexOf查找数组中的键码来检查列表中的同时键。

于 2016-02-14T05:05:24.710 回答
0

ctrl+s在 React 中保存

useEffect(() => {
        document.onkeydown = function (e) {
            if (e.ctrlKey == true && e.key == 's') {
                e.preventDefault() // to override browser's default save page feature
                alert('ctrl+s is working for save!') // invoke your API to save
            }
        }
}, [])
于 2021-08-27T07:51:57.253 回答