javascript 检测输入框中的粘贴
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5450449/
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
Detect paste in input box
提问by Itay.B
I have a input box, and I would like to use vbscript or javascript (no jquery) to capture the paste event.
我有一个输入框,我想使用 vbscript 或 javascript(没有 jquery)来捕获粘贴事件。
回答by philant
Use the onpaste event to capture the event and do what you need in Javascript. E.g. to disable the paste in an input text field:
使用 onpaste 事件捕获事件并在 Javascript 中执行您需要的操作。例如,禁用输入文本字段中的粘贴:
<input type="text" onpaste="return false;" />
回答by Jared Farrish
回答by Sebastian Td
Just for future readers finding this as I did.
仅供未来的读者像我一样发现这一点。
You will still be able to drop text into an input with the onpaste="return false;" attribute. If you want to avoid this, you can do something like this:
您仍然可以使用 onpaste="return false;" 将文本放入输入中 属性。如果你想避免这种情况,你可以这样做:
var input_element = document.getElementById("Element");
input_element.addEventListener("drop", function (event) {
var types = event.dataTransfer.types;
if (types.length > 2 || types.indexOf("text/plain") === -1)
event.preventDefault();
else{
setTimeout(function(){ input_element.value = ""; },10);
}
}, false);