How to keep the text formatting on pasting in jQue

2019-06-07 12:09发布

问题:

I'd like to edit the text before it is pasted.

My current code is:

element.on('paste', function (event) {
    event.preventDefault();
    var clipboardData = (event.originalEvent || event).clipboardData;
    var text = clipboardData.getData('text/html') || clipboardData.getData('text/plain') ||
    //document.execCommand('insertHTML', false, text);  <--     
});

I used this first but it sometimes fails and malforms the text formatting which I want to keep.

I think that using another function than execCommand will fix this bug, because I read more people are having trouble with this function and it has very limited support

回答1:

element.on('paste', function (event) {
  event.preventDefault();
  var clipboardData = (event.originalEvent || event).clipboardData;
  var text = clipboardData.getData('text/html') || clipboardData.getData('text/plain') ||
  document.execCommand('insertHTML', false, '<pre>' + text + '</pre>');
});