How can I add a JavaScript keyboard shortcut to an existing JavaScript Function?

前端 未结 8 1919
忘了有多久
忘了有多久 2020-11-27 04:03

Here is my code:

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

I wo

8条回答
  •  自闭症患者
    2020-11-27 04:55

    Catch the key code and then call your function. This example catches the ESC key and calls your function:

    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);
        });
    });
    

    You'll need JQUERY for this example.

提交回复
热议问题