HTML : How to modify multi-line copied text in IE

2019-08-22 05:51发布

问题:

When we copy some text separated by new line and try to paste it in a text field in IE, the text gets truncated starting from the first new line character. In Firefox and Chrome, the new line character simply converts to a space. I am required to implement a uniform behaviour for all of these browsers.

If I can get hold of the copied text, I can convert all \r\n to \n and then all \n to the space character, but I can't think of a way to access the copied text before its truncated

回答1:

For IE only!! You can get the information from window.clipboardData as shown here:

$('input:text').on('paste', function(ev) {
    var multiCellTarget = $(this);
    setTimeout(function() {
        var cells = window.clipboardData.getData('text').split(/\s+/);
        if (cells.length > 1) {
            // [... do stuff with cells]
        }
    }, 20);
});

The 20 ms timeout is a trick to work around the problem that the clipboard data does not seem to be available at the time jquery kicks off the paste event.