简体   繁体   English

在Javascript中拦截粘贴事件

[英]Intercept paste event in Javascript

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中的粘贴事件并获取原始值,更改它,并将关联的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? 这可能吗?

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”处理程序拦截粘贴事件,并通过在IE中使用“ window.clipboardData.getData('Text') ”或“ 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所指出的,如果使用jQuery,则需要使用“ e.originalEvent.clipboardData ”。

As it happens, I answered a similar question earlier today. 碰巧的是,我今天早些时候回答了类似的问题 In short, you need a hack to redirect the caret to an off-screen textarea when the paste event fires. 简而言之,当粘贴事件触发时,您需要一个hack来将插入符重定向到屏幕外的textarea。

$(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');
    }
});

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年发现的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. 如果用户键入空格或BS或Del然后粘贴,则不会进行修剪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM