Preventing ctrl+z in browser

Deadly 提交于 2019-12-12 13:18:23

问题


I used the code sample below to disable ctrl + c and ctrl + v and it works. I used similar mechanics to disable ctrl + z (undo) in the browser but it doesn't work.

var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67, zKey = 90;

$('body').keydown(function(e) {
  if (e.keyCode == 17 || e.keyCode == 91) {
    ctrlDown = true;
  };
}).keyup(function(e) {
  if (e.keyCode == 17 || e.keyCode == 91) {
    ctrlDown = false;
  };
});

$("body").keydown(function(e){
  if ((ctrlDown && e.keyCode == zKey) || (ctrlDown && e.keyCode == vKey) || (ctrlDown && e.keyCode == cKey)) {
    e.preventDefault();
    return false;
  }
});

回答1:


I can see from testing that the if condition in your $("body").keydown handler isn't firing. While ctrlDown does get set to true, for some reason your series of conditions isn't firing. I don't think storing key codes and ctrl state in the global scope is going to be a great approach.

Rather than a separate handler testing for ctrl usage, it'd be easier to test just within the "z" keydown handler for whether Ctrl (or Meta i.e. command, to be Mac-compatible as well) is being used. The event object has Boolean properties ctrlKey and metaKey for just such occasions. So your code would be:

$("body").keydown(function(e){
  var zKey = 90;
  if ((e.ctrlKey || e.metaKey) && e.keyCode == zKey) {
    e.preventDefault();
    return false;
  }
});

This is still not quite as robust as it could be, since you'd want to only check metaKey on Mac and check ctrl on Linux/Windows to handle a few edge cases where someone might press "Meta + Z" (does that do anything in Windows?), but it's close. It works on my Mac.


A caution—& you've probably already considered this—that disabling OS-level keyboard shortcuts can be really dangerous. It messes with user expectations in a bad way. If you're overriding to do something similar in a big browser app, that makes perfect sense, though. Be careful!



来源:https://stackoverflow.com/questions/32150987/preventing-ctrlz-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!