1

I have an issue with the onpaste event in JS. I need to copy the clipboard content into 2 text boxes by splitting it into half. I am using the code below.

function paste(){
document.getElementById("txt1").value = clipboarddata.substr(0,2);
document.getElementById("txt2").value = clipboarddata.substr(2,4);
}

this function is called on the onpaste event. The content gets pasted but after the function the entire string is again paste in the box into which the data was paste.

Can i by any chance cancel the event by using cancelbubble etc to cancel the event in the paste() function. ??

Thanks in advance

4

1 回答 1

0

我知道这有点晚了,但是对于任何寻找这个的人来说,这里有一种方法:

在你做了你必须做的事情之后,你必须这样做return false;这将阻止默认处理程序运行。

这是一个演示:

HTML

<textarea id="txt1"></textarea>
<textarea id="txt2"></textarea>

Javascript

var myElement = document.getElementById('txt1');
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');
   }
   document.getElementById("txt1").value = pastedText.substr(0, pastedText.length / 2);
   document.getElementById("txt2").value = pastedText.substr(pastedText.length / 2 + 1, pastedText.length);
   return false; // Prevent the default handler from running.
};

jsfiddle demo

于 2013-10-21T13:40:45.753 回答