Intercept paste event in Javascript

2019-01-03 09:23发布

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?

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?

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-03 09:53
$(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');
    }
});
查看更多
姐就是有狂的资本
3楼-- · 2019-01-03 09:55

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.

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.

查看更多
仙女界的扛把子
4楼-- · 2019-01-03 09:58

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.

查看更多
趁早两清
5楼-- · 2019-01-03 10:08

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:

$(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.

查看更多
登录 后发表回答