防止浏览器中的ctrl + z [英] Preventing ctrl+z in browser

查看:365
本文介绍了防止浏览器中的ctrl + z的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码示例来禁用 ctrl + c ctrl + v 并且它可以正常工作。我在浏览器中使用类似的机制来禁用 ctrl + z (撤消),但它不起作用。

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;
  }
});


推荐答案

我可以从测试中看到你的if条件$(body)。keydown处理程序没有触发。虽然ctrlDown确实设置为 true ,但由于某种原因,您的一系列条件未触发。我不认为在全局范围内存储密钥代码和ctrl状态将是一个很好的方法。

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.

而不是单独的处理程序测试ctrl使用,它' d更容易在zkeydown处理程序中测试是否正在使用Ctrl(或Meta即命令,与Mac兼容)。 事件对象具有布尔属性 ctrlKey metaKey 这样的场合。所以你的代码是:

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;
  }
});

这仍然没有那么强大,因为你只想检查metaKey在Mac上并检查Linux / Windows上的ctrl来处理一些边缘情况,有人可能会按下Meta + Z(这在Windows中做了什么?),但它已经接近了。它适用于我的Mac。

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!

这篇关于防止浏览器中的ctrl + z的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆