gpt4 book ai didi

javascript - 在 Mac 上的 Chrome 上无法捕捉到 Cmd-S

转载 作者:行者123 更新时间:2023-12-03 06:13:47 25 4
gpt4 key购买 nike

我试图在浏览器上同时捕获 Ctrl-SCmd-S我的网络应用程序的操作系统兼容性。我在这里看到了一个关于如何执行此操作的帖子:jquery keypress event for cmd+s AND ctrl+s

我的代码中有以下片段:

$(document).keypress(function(event) {
if (event.which == 115 && (event.ctrlKey||event.metaKey)|| (event.which == 19)) {
event.preventDefault();
save();
return false;
}
return true;
});

其中 save() 是一个 JavaScript 函数,将来会发送 AJAX 请求,但现在只有 alert('Saved!');

但是,虽然这会捕获 Ctrl-S,但它不会捕获 Chrome 上的 Cmd-S ,而不是像平常一样打开保存网页对话框。我看到该页面上的其他人也遇到了同样的问题,但我没有找到解决方案。

提前致谢!

最佳答案

太有创意了!!!太棒了@Sam0。

对于想要简单 JavaScript 版本、不带 JQuery 的初学者(即使当你明白这一点时,$() 只是允许你轻松指定 CSS 选择器),这是脚本:

/**
* CMD+S/CTRL+S
* Function listens first to cmd or ctrl keys.
* Metaflag variable becomes true if one of those keys is pressed.
* If key "s" is then listened - before 100ms delay -, it launches your
instructions.
* Without timer, "s" could happen (e.g.) 1 hour after alteration key pressed,
* even if your just type "s" in a text. Timer is a trick to avoid this.
*/

(function(){
var metaflag = false;
document.addEventListener('keydown',function(event) {
if (event.ctrlKey||event.metaKey || event.which === 19) {
// ctrl cmd(mac) break/pause key(?)
metaflag = true;
timer = Date.now();
}
if(metaflag && event.which === 83 && Date.now()-timer<100){
// "S" //100ms
event.preventDefault(); // maybe not necessary
//...Your instructions...
metaflag = false;
}
});
})();

关于javascript - 在 Mac 上的 Chrome 上无法捕捉到 Cmd-S,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39198814/

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