问题
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