gpt4 book ai didi

javascript - 使用 Ctrl+v 或右键单击 -> 粘贴检测粘贴的文本

转载 作者:行者123 更新时间:2023-12-03 03:09:20 26 4
gpt4 key购买 nike

如何使用 JavaScript 检测用户将哪些文本粘贴到文本区域?

最佳答案

您可以使用粘贴事件来检测大多数浏览器中的粘贴(尤其是 Firefox 2)。当您处理粘贴事件时,记录当前选择,然后设置一个简短的计时器,在粘贴完成后调用函数。然后,该函数可以比较长度并了解在哪里查找粘贴的内容。像下面这样的东西。为了简洁起见,获取文本区域选择的函数在 IE 中不起作用。请参阅此处的相关内容:How to get the start and end points of selection in text area?

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
});

关于javascript - 使用 Ctrl+v 或右键单击 -> 粘贴检测粘贴的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3211505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com