【问题标题】:Can't catch Cmd-S on Chrome on Mac无法在 Mac 上的 Chrome 上捕获 Cmd-S
【发布时间】:2017-01-05 01:05:59
【问题描述】:

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

我的代码中有以下 sn-p:

$(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 ,而不是像往常一样打开保存网页对话框。我看到该页面上的其他人也遇到了同样的问题,但我没有找到解决方案。

提前致谢!

【问题讨论】:

  • 还要注意,the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.(来自官方jQuery doc for keypress)。您可能要考虑根本不使用keypress
  • @filoxo 感谢您告诉我 :)

标签: javascript jquery macos google-chrome osx-yosemite


【解决方案1】:

好巧妙!!!太棒了@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;
    }
  });
})();

【讨论】:

  • 效果很好,可惜没有更容易捕捉的方法!
【解决方案2】:

我认为你拥有的 keypress 不会以完全相同的方式注册元键,请参阅:Diffrence between keyup keydown keypress and input events 这是一个似乎使用 keydown 工作的小提琴,然后按顺序捕获每个。希望有帮助吗?

var metaflag = false;

$(document).on({
	keydown: function(event) {
    if (event.ctrlKey||event.metaKey || event.which === 19) {
      event.preventDefault();
      $('.monitor').text('key '+event.which);
      metaflag = true;
    }
  	if( metaflag && event.which === 83 ){ // 83 = s?
      event.preventDefault(); // maybe not necessary
      $('.display').text('saving?');
      metaflag = false;
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='monitor'></div>
<div class='display'></div>

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 2014-03-06
    • 2017-03-24
    • 2017-05-04
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多