在JavaScript中拦截粘贴数据 [英] Intercept Paste data in JavaScript

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

问题描述

我从在Javascript中拦截粘贴事件中获得了以下代码。

I got the following code from Intercept paste event in Javascript.

我需要在粘贴之前得到它,否则我会丢失我需要保存的\ n字符。

I need to get it before it is pasted, otherwise i lose the "\n" characters i need to save.

它可以很好地拦截一个带有id的元素的剪贴板数据。我需要它来处理所有输入元素。当我尝试使用jQuery来获取输入元素时没有。

It works great to intercept clipboard data for one element with an id. I need it to work on all input elements. When I try to use jQuery to get the input elements nothing.

感谢任何帮助。

var paster = function () {
    var myElement = document.getElementByTagName('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');
        }
        processExcel(pastedText); // Process and handle text...
        return false; // Prevent the default handler from running.
    };
}


推荐答案

只需添加粘贴事件监听器到文档。

Just add a paste event listener to the document.

document.addEventListener("paste", function (e) {
    console.log(e.target.id);
    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');
    }
    e.preventDefault();
    e.target.value = "You just pasted '" + pastedText + "'";
    return false;
});

小提琴

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

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