使用ctrl + v或右键单击检测粘贴的文本 - >糊 [英] Detect pasted text with ctrl+v or right click -> paste

查看:161
本文介绍了使用ctrl + v或右键单击检测粘贴的文本 - >糊的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用JS检测用户在textarea中粘贴的文本?

How to detect what text the user pastes in textarea with JS?

推荐答案

您可以使用粘贴事件来检测粘贴在大多数浏览器中(特别是Firefox 2)。处理粘贴事件时,记录当前选择,然后设置一个在粘贴完成后调用函数的简短计时器。然后,此函数可以比较长度并知道在哪里查找粘贴的内容。像下面这样的东西。为简洁起见,获取textarea选择的函数在IE中不起作用。请看这里做的事情:如何在文本区域中获取选择的起点和终点?

You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: 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
});

这篇关于使用ctrl + v或右键单击检测粘贴的文本 - >糊的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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