Javascript 在Javascript中拦截粘贴事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6035071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:58:19  来源:igfitidea点击:

Intercept paste event in Javascript

javascriptdomcopy-pastepaste

提问by Brandon

Is there a way to intercept the paste event in JavaScript and get the raw value, change it, and set the associated DOM element's value to be the modified value?

有没有办法拦截 JavaScript 中的 paste 事件并获取原始值,更改它,并将关联的 DOM 元素的值设置为修改后的值?

For instance, I have a user trying to copy and paste a string with spaces in it and the string's length exceeds the max length of my text box. I want to intercept the text, remove the spaces, and then set the text box's value with the change value.

例如,我有一个用户试图复制和粘贴一个带有空格的字符串,并且该字符串的长度超过了我的文本框的最大长度。我想截取文本,删除空格,然后使用更改值设置文本框的值。

Is this possible?

这可能吗?

回答by maerics

You can intercept the paste event by attaching an "onpaste" handler and get the pasted text by using "window.clipboardData.getData('Text')" in IE or "event.clipboardData.getData('text/plain')" in other browsers.

您可以通过附加“onpaste”处理程序来拦截粘贴事件,并window.clipboardData.getData('Text')在 IE 中使用“ ”或event.clipboardData.getData('text/plain')在其他浏览器中使用“ ”获取粘贴的文本。

For example:

例如:

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

As @pimvdb notes, you will need to use "e.originalEvent.clipboardData" if using jQuery.

正如@pimvdb 所指出的,e.originalEvent.clipboardData如果使用 jQuery ,您将需要使用“ ”。

回答by Tim Down

As it happens, I answered a similar questionearlier today. In short, you need a hack to redirect the caret to an off-screen textarea when the paste event fires.

碰巧,我今天早些时候回答了一个类似的问题。简而言之,当粘贴事件触发时,您需要一个 hack 将插入符号重定向到屏幕外的文本区域。

回答by Cyrus

$(document).ready(function() {
    $("#editor").bind('paste', function (e){
        $(e.target).keyup(getInput);
    });

    function getInput(e){
        var inputText = $(e.target).val();
        alert(inputText);
        $(e.target).unbind('keyup');
    }
});

回答by Craig Silver

I needed to implement a "trim" on whatever was pasted (remove all leading and trailing whitespace) while still allowing the use of the spacebar.

我需要对粘贴的任何内容进行“修剪”(删除所有前导和尾随空格),同时仍然允许使用空格键。

For Ctrl+V, Shift+Insert and mouse right-click Paste, here is what I found worked in FF, IE11 and Chrome as of 2017-04-22:

对于 Ctrl+V、Shift+Insert 和鼠标右键单击粘贴,以下是我在 2017 年 4 月 22 日在 FF、IE11 和 Chrome 中发现的工作:

$(document).ready(function() {
    var lastKeyCode = 0;

    $('input[type="text"]').bind('keydown', function(e) {
        lastKeyCode = e.keyCode;
    });
    // Bind on the input having changed.  As long as the previous character
    // was not a space, BS or Del, trim the input.
    $('input[type="text"]').bind('input', function(e) {
        if(lastKeyCode != 32 && lastKeyCode != 8 && lastKeyCode != 46) {
            $(this).val($(this).val().replace(/^\s+|\s+$/g, ''));
        }
    });
});

Two caveats:

两个注意事项:

  1. If there is already text when the paste occurs, trimming occurs on the entire result, not just what it being pasted.

  2. If the user types space or BS or Del and then pastes, trimming will not occur.

  1. 如果粘贴时已经有文本,则会对整个结果进行修剪,而不仅仅是粘贴的内容。

  2. 如果用户键入空格或 BS 或 Del 然后粘贴,则不会发生修剪。