如何向现有 JavaScript 函数添加键盘快捷键?

发布于 2024-08-26 14:47:13 字数 455 浏览 9 评论 0 原文

这是我的代码:

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

Here is my code:

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

I would like to add a keyboard shortcut to this code, how can I do this so that the function can also be executed when a button is clicked too?

Tried to add an else if statement but it doesn't work, any ideas?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

野味少女 2024-09-02 14:47:13

处理 document 上的 keyup 事件。

请注意,KeyboardEvent.keyCode已弃用。假设问题代码的意思是通过物理位置检查按键, KeyboardEvent.code 是现在执行此操作的正确方法。

// 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.code === 'ArrowDown') {
        // call your function to do the thing
        pauseSound();
    }
}
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);

Handle the keyup event on the document.

Note that KeyboardEvent.keyCode was deprecated. Assuming the question code means to check keys by physical location, KeyboardEvent.code is the proper way to do so now.

// 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.code === 'ArrowDown') {
        // call your function to do the thing
        pauseSound();
    }
}
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);
倾其所爱 2024-09-02 14:47:13

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

在此示例中按 ALT+a

document.onkeyup = function () {
  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”属性了解更多信息。

If you want to trigger an event after pressing a key, try:

In this example press ALT+a:

document.onkeyup = function () {
  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;
  }
}

Here is a fiddle: https://jsfiddle.net/dmtf6n27/38/

Please also note there is a difference for the keycode numbers, whether you are using onkeypress or onkeyup. W3 Schools' "KeyboardEvent keyCode" Property has more information.

暖树树初阳… 2024-09-02 14:47:13
//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. ......
//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. ......
山人契 2024-09-02 14:47:13

这是我的解决方案:

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 检测到按键被释放时,数组将被重置,这意味着此时没有按键被按下。
  • 每次它都会检查快捷方式是否匹配。如果确实如此,它将调用处理程序。

Here's my solution:

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!")
})
  • When you call my function, it will create an array called currentKeys; these are the keys that will are being held down at that moment.
  • Every time a key is pressed, sensed because of onkeydown, it is added to the currentKeys array.
  • When the keys are released, sensed because of onkeyup, the array is reset meaning that no keys are being pressed at that moment.
  • Each time it will check if the shortcut matches. If it does it will call the handler.
挥剑断情 2024-09-02 14:47:13

这对我有用

document.onkeyup=function(e){
  var e = e || window.event;
  if(e.which == 37) {
    $("#prev").click()
  }else if(e.which == 39){
    $("#next").click()
  }
}

This worked for me

document.onkeyup=function(e){
  var e = e || window.event;
  if(e.which == 37) {
    $("#prev").click()
  }else if(e.which == 39){
    $("#next").click()
  }
}
泪冰清 2024-09-02 14:47:13

捕获关键代码,然后调用您的函数。此示例捕获 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 对于这个例子。

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.

南城旧梦 2024-09-02 14:47:13

这些似乎都使用已弃用的 keyCodewhich 属性。以下是使用 jQuery 连接事件的未弃用版本:

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

注意:Ctrl+t 可能已被指定用于打开新的浏览器选项卡。

These appear to all be using the deprecated keyCode and which properties. Here is a non-deprecated version using jQuery to wire up the event:

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

Note: Ctrl+t may already be assigned to opening a new browser tab.

王权女流氓 2024-09-02 14:47:13

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

注释位于代码中,但简而言之,它在 document 上设置了一个侦听器,并使用您想要侦听的按键组合来管理哈希。

  • 当您注册要侦听的键(组合)时,您提交键代码(最好作为从导出的“key”属性获取的常量,您可以自己添加更多常量)、处理程序函数以及可能的选项哈希,其中您说您对该键的计划是否涉及 Ctrl 和/或 Alt 键。
  • 当您取消注册密钥(组合)时,您只需提交密钥和 Ctrl/Alt 的可选哈希值。
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 字符代码(Key Codes)找到很多keyCodes可以使用,

Here's some stuff to use if you want. You can register a bunch of keys and handler with it.

Comments are in the code, but in short it sets up a listener on the document and manages a hash with the key combinations for which you want to listen.

  • When you register a key (combination) to listen for, you submit the keycode (preferrably as a constant taken from the exported "key" property, to which you can add more constants for yourself), a handler function and possibly an options hash where you say if the Ctrl and/or Alt key are involved in your plans for this key.
  • When you de-register a key (combination) you just submit the key and the optional hash for 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});

It is not terribly tested, but seemed to work OK.

Look at Javascript Char Codes (Key Codes) to find a lot of keyCodes to use,

热血少△年 2024-09-02 14:47:13

解决方案:

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 查找数组中的键代码,检查列表中是否有同时出现的键。

Solution:

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

Explanation:
I ran into this same problem and came up with my own solution. e.metaKey didn't seem to work with the keyup event in Chrome and Safari. However, I'm not sure if it was specific to my application since I had other algorithms blocking some key events and I may have mistakenly blocked the meta key.

This algorithm monitors for keys going down and then adds them to a list of keys that are currently being pressed. When released, the key is removed from the list. Check for simultaneous keys in the list by using indexOf to find key codes in the array.

甜宝宝 2024-09-02 14:47:13

在 React 中使用 ctrl+s 保存

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
            }
        }
}, [])

Saving with ctrl+s in 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
            }
        }
}, [])
忆梦 2024-09-02 14:47:13

其中许多答案建议强制覆盖 document.onkeypress。这不是一个好的做法,因为它只允许分配单个事件处理程序。如果之前由另一个脚本设置了任何其他处理程序,它们将被您的函数替换。如果您稍后分配另一个处理程序,它将替换您在此处分配的处理程序。

更好的方法是使用 addEventListener 附加您的键盘快捷键。这允许您根据需要附加尽可能多的处理程序,并且不会干扰任何可能已附加自己的外部库。

此外,UIEvent.which< /a> 属性从未标准化,不应使用。 KeyboardEvent.keyCode 也是如此。当前用于检查按下哪个键的符合标准属性是KeyboardEvent.key。在可用值的完整列表

为了获得最佳性能,如果您需要修饰键 未被按下。同样,不要使用多个 keypress 事件监听器,而是使用一个带有 swtich/case 语句对您要处理的每个键做出适当的反应。

另外,不要忘记使用 取消密钥的默认行为如有必要,Event.preventDefault。不过,有一些快捷键无法覆盖 就像ctrl+w

document.addEventListener('keypress', event => {
  if (!event.ctrlKey) { return; }
  event.preventDefault();
  switch (event.key) {
    case 'x' : doSomething(); break
    case 'z' : doSomethingElse(); break;
    default : console.log('unhandled key was pressed');
  }
});

Many of these answers suggest forcibly overriding document.onkeypress. This is not a good practice because it only allows for a single event handler to be assigned. If any other handlers were previously set up by another script they will be replaced by your function. If you assign another handler later, it will replace the one you assigned here.

A much better approach is to use addEventListener to attach your keyboard shortcut. This allows you to attach as many handlers as necessary and will not interfere with any external libraries that may have attached their own.

Additionally, the UIEvent.which property was never standardized and should not be used. The same goes for KeyboardEvent.keyCode. The current standards compliant property you should use to check which key was pressed is KeyboardEvent.key. Find the key you want in the full list of available values.

For best performance, return early if your desired modifier key is not pressed. As well, rather than having multiple keypress event listeners, use a single one with a swtich/case statement to react appropriately to each key that you want to handle.

Also, do not forget to cancel the default behavior of the key with Event.preventDefault if necessary. Though, there are some shortcuts that you cannot override like ctrl+w.

document.addEventListener('keypress', event => {
  if (!event.ctrlKey) { return; }
  event.preventDefault();
  switch (event.key) {
    case 'x' : doSomething(); break
    case 'z' : doSomethingElse(); break;
    default : console.log('unhandled key was pressed');
  }
});
〃安静 2024-09-02 14:47:13

这适用于 Ctrl + Shift + L

document.onkeydown = function (e) {
  // Detect if Ctrl + Shift is pressed together
  if (e.ctrlKey && e.shiftKey) {
    // Detect if L is pressed after Ctrl + Shift
    if (e.key == "L")
    {
      // Your code...
    }
  }
};

This works for Ctrl + Shift + L

document.onkeydown = function (e) {
  // Detect if Ctrl + Shift is pressed together
  if (e.ctrlKey && e.shiftKey) {
    // Detect if L is pressed after Ctrl + Shift
    if (e.key == "L")
    {
      // Your code...
    }
  }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文