Tim*_*own 19
您可以使用粘贴事件来检测大多数浏览器中的粘贴(特别是Firefox 2).处理粘贴事件时,记录当前选择,然后设置一个在粘贴完成后调用函数的简短计时器.然后,此函数可以比较长度并知道在哪里查找粘贴的内容.像下面这样的东西.为简洁起见,获取textarea选择的函数在IE中不起作用.请看这里做的事情:如何在文本区域中获取选择的起点和终点?
function getTextAreaSelection(textarea) {
var start = textarea.selectionStart, end = textarea.selectionEnd;
return {
start: start,
end: end,
length: end - start,
text: textarea.value.slice(start, end)
};
}
function detectPaste(textarea, callback) {
textarea.onpaste = function() {
var sel = getTextAreaSelection(textarea);
var initialLength = textarea.value.length;
window.setTimeout(function() {
var val = textarea.value;
var pastedTextLength = val.length - (initialLength - sel.length);
var end = sel.start + pastedTextLength;
callback({
start: sel.start,
end: end,
length: pastedTextLength,
text: val.slice(sel.start, end)
});
}, 1);
};
}
var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
alert(pasteInfo.text);
// pasteInfo also has properties for the start and end character
// index and length of the pasted text
});
Run Code Online (Sandbox Code Playgroud)
Abd*_*UMI 10
HTML5onpaste不仅提供<input/>,还提供可编辑的元素(<p contenteditable="true" />,...)
<input type="text" onpaste="myFunction()" value="Paste something in here">
Run Code Online (Sandbox Code Playgroud)