gpt4 book ai didi

javascript - 如何在 JavaScript 中触发键盘快捷键功能?

转载 作者:行者123 更新时间:2023-12-03 10:26:14 26 4
gpt4 key购买 nike

我的网站有记录功能。如果用户按下 Ctrl+Alt+R 录音就会开始。现在我想在我的 html 页面中有一个名为 RECORD 的按钮,这样当用户点击该按钮时就会开始录制。

<button type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="top" onclick="record_session()" title="Start Recording">Record</button>

在我的下面的函数中

function record_session(){
//how can i trigger or initiate ctrl+alt+r here??
}

最佳答案

如果您使用 jQuery,您可以添加按键事件:

$(document).keypress(function(e) {
if (e.which === 114 && e.ctrlKey && e.altKey) {
record_session();
}
});

更新:

var enable_keypress = false;
function record_session(){
enable_keypress = true;
}
$(document).keypress(function(e) {
if (enable_keypress) {
if (e.which === 114 && e.ctrlKey && e.altKey) { // ctrl+alt+r

}
}
});

更新2

要触发键盘事件,您可以使用以下命令:

jQuery:

function keydown(ctrl, alt, shift, which, key) {
var e = $.Event("keydown");
e.ctrlKey = ctrl;
e.altKey = alt;
e.shiftKey = shift;
if (typeof which === 'string') {
key = which;
which = key.toUpperCase().charCodeAt(0);
}
e.key = key;
e.which = e.keyCode = which;
return e;
}
function keypress(key) {
var e = $.Event("keypress");
e.key = key;
e.which = e.keyCode = 0;
return e;
}
function shortcut({
ctrl = false,
alt = false,
shift = false,
which,
key
}) {
var doc = $(document.documentElement || window);
if (typeof which === 'string') {
key = which;
which = key.toUpperCase().charCodeAt(0);
}
doc.trigger(keydown(ctrl, alt, shift, which, key));
doc.trigger(keypress(key));
}

您可以使用快捷键来触发 keydown 和 keypress:

shortcut({ctrl: true, alt: true, which: 'r'});

如果你有做不同事情的监听器(我在 jQuery Terminal 的测试中有这个);

native 代码:

 function shortcut({chr, ctrlKey = false, altKey = false}) {
var lowerChr = chr.toLowerCase();
var upperChr = chr.toUpperCase();
var keydownCode = upperChr.charCodeAt(0);
var e = new KeyboardEvent("keydown", {
key: lowerChr,
code: "Key" + upperChr,
ctrlKey,
altKey,
keyCode: keydownCode,
which: keydownCode
});
var keypressCode = lowerChr.charCodeAt(0);
document.documentElement.dispatchEvent(e);
var e = new KeyboardEvent("keypress", {
key: lowerChr,
ctrlKey,
altKey,
charCode: keypressCode,
keyCode: keypressCode,
which: keypressCode
});
document.documentElement.dispatchEvent(e);
}

关于javascript - 如何在 JavaScript 中触发键盘快捷键功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com