javascript 如何使用正则表达式检测 CTRL+C 和 CTRL+V 按键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22092762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to detect CTRL+C and CTRL+V key pressing using regular expression?
提问by preeth
I have blocked all aTOz character input for my text field using regular expression in my JavaScript but as I have blocked entire alphabets I am not able to perform CTRL+Cand CTRL+V, here is my regular expression goes:
我在 JavaScript 中使用正则表达式阻止了文本字段的所有 aTOz 字符输入,但是由于我阻止了整个字母表,我无法执行CTRL+C和CTRL+ V,这是我的正则表达式:
var reValidChars = /[\x08\x0D\d]/;
iKeyCode = objEvent.charCode;
strKey = String.fromCharCode(iKeyCode);
if (!reValidChars.test(strKey)) {
return false;
}
Could you please help me in this issue. Thanks in advance
你能帮我解决这个问题吗?提前致谢
回答by nanobash
You can't detect key pressing with RegExp, though you can like following:
您无法使用 RegExp 检测按键按下,但您可以喜欢以下内容:
document.body.addEventListener("keydown",function(e){
e = e || window.event;
var key = e.which || e.keyCode; // keyCode detection
var ctrl = e.ctrlKey ? e.ctrlKey : ((key === 17) ? true : false); // ctrl detection
if ( key == 86 && ctrl ) {
console.log("Ctrl + V Pressed !");
} else if ( key == 67 && ctrl ) {
console.log("Ctrl + C Pressed !");
}
},false);
回答by DOOManiac
Use the paste
event to take an action upon pasting from the clipboard.
使用该paste
事件在从剪贴板粘贴时采取行动。
Note that users have many, many ways of getting content into your text boxes!
请注意,用户有很多很多方法可以将内容放入您的文本框中!
- Typing
- Autocomplete (doesn't fire key events in all browsers)
- Paste via menu
- Paste via keyboard shortcut
- Drag & Drop highlighted text from other programs
- Etc.
- 打字
- 自动完成(不会在所有浏览器中触发关键事件)
- 通过菜单粘贴
- 通过键盘快捷键粘贴
- 从其他程序拖放突出显示的文本
- 等等。
So instead of trapping things only on keyboard entry (keyup
), you need to trap them at the actual paste level and other events too! This means you may also need to observe any or all of these events, depending on your situation:
因此keyup
,与其仅在键盘输入 ( )上捕获内容,还需要在实际粘贴级别和其他事件中捕获它们!这意味着您可能还需要观察任何或所有这些事件,具体取决于您的情况:
回答by Jacek
If you want to detect copying and pasting to your control you should use control events instead of regexp.
如果您想检测复制和粘贴到您的控件,您应该使用控件事件而不是正则表达式。
document.addEventListener('copy', function(e){
e.clipboardData.setData('text/plain', 'Hello, world!');
e.clipboardData.setData('text/html', '<b>Hello, world!</b>');
e.preventDefault(); // We want to write our data to the clipboard, not data from any user selection
});
document.querySelector('textarea').addEventListener('paste', (e) => {
console.log(e);
});