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

ドキュメントのキーアップイベントのイベントハンドラーは、適切な解決策のようです。

注: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 に答える
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リッスンするキーの組み合わせでハッシュを管理します。

  • リッスンするキー (組み合わせ) を登録するときは、キーコード (できればエクスポートされた「キー」プロパティから取得した定数として、自分で定数を追加できます)、ハンドラー関数、および場合によってはオプション ハッシュを送信します。Ctrland/orAltキーがこのキーの計画に含まれているかどうかを示します。
  • キー (組み合わせ) を登録解除するときは、キーとオプションの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

これらはすべて、非推奨のkeyCodeandwhichプロパティを使用しているようです。以下は、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

ctrl+sReact での保存

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 に答える