在Javascript中拦截粘贴事件 [英] Intercept paste event in Javascript

查看:108
本文介绍了在Javascript中拦截粘贴事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法拦截JavaScript中的粘贴事件并获取原始值,更改它,并将关联的DOM元素的值设置为修改值?



例如,我有一个用户尝试复制和粘贴一个空格的字符串,字符串的长度超过了我的文本框的最大长度。我想拦截文本,删除空格,然后用变更值设置文本框的值。



这是可能吗?

解决方案

您可以通过附加onpaste处理程序来拦截粘贴事件,并使用 event.clipboardData.getData('text / plain')中的Text)



例如:

  var myElement = document.getElementById('pasteElement'); 
myElement.onpaste = function(e){
var pastedText = undefined;
if(window.clipboardData&&& window.clipboardData.getData){// IE
pastedText = window.clipboardData.getData('Text');
} else if(e.clipboardData&& e.clipboardData.getData){
pastedText = e.clipboardData.getData('text / plain');
}
alert(pastedText); //处理和处理文本...
return false; //防止默认处理程序运行。
};

由于@pimvdb注意到,您将需要使用 e.originalEvent。 clipboardData 如果使用jQuery。


Is there a way to intercept the paste event in JavaScript and get the raw value, change it, and set the associated DOM element's value to be the modified value?

For instance, I have a user trying to copy and paste a string with spaces in it and the string's length exceeds the max length of my text box. I want to intercept the text, remove the spaces, and then set the text box's value with the change value.

Is this possible?

解决方案

You can intercept the paste event by attaching an "onpaste" handler and get the pasted text by using "window.clipboardData.getData('Text')" in IE or "event.clipboardData.getData('text/plain')" in other browsers.

For example:

var myElement = document.getElementById('pasteElement');
myElement.onpaste = function(e) {
  var pastedText = undefined;
  if (window.clipboardData && window.clipboardData.getData) { // IE
    pastedText = window.clipboardData.getData('Text');
  } else if (e.clipboardData && e.clipboardData.getData) {
    pastedText = e.clipboardData.getData('text/plain');
  }
  alert(pastedText); // Process and handle text...
  return false; // Prevent the default handler from running.
};

As @pimvdb notes, you will need to use "e.originalEvent.clipboardData" if using jQuery.

这篇关于在Javascript中拦截粘贴事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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