Paste event listener on Internet Explorer getting wrong arguments

若如初见. 提交于 2019-12-05 14:18:54

问题


I'm handling the paste events for a contenteditable to clean all HTML markers before paste. All Works fine in Firefox and Chrome. But when I test my code in IE11, the event object passed is not a ClipboardEvent but a DragEvent.

Is there something wrong with my code? If I add the listener as the code bellow, should I get the clipboard event. Why I'm getting drag?

editable.addEventListener('paste', pasteHandler, false);

http://jsfiddle.net/vepo/4t2ofv8n/

To test the example above, I'm copy a text from Chrome and paste into IE. But I you copy any text from IE will get the same error.


回答1:


EDIT

$(document).ready(function(){
    var editable = document.getElementById('editable-div');
    var pasteHandler = function(e){
        if(e.clipboardData && e.clipboardData.getData) {
            var pastedText = "";
            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);
        }
        else{
            alert('Not paste object!');
        }
    };
    editable.addEventListener('paste', pasteHandler, false);
});

here I handle the IE Version and the other browsers as well.

JSFiddle




回答2:


e.clipboardData was always null for me on IE, so I came up with this:

var pastedText = '';
if (typeof e.clipboardData === 'undefined')
    pastedText = window.clipboardData.getData('Text')
else
    pastedText = e.clipboardData.getData('text/plain')



回答3:


e.originalEvent.clipboardData.getData('text/plain') works for safari, chrome, firefox and safari and chrome on an Ipad.

window.clipboardData.getData('text') works for Internet Explorer and Edge.

Note: e.originalEvent.clipboardData.getData('text') works for desktop browsers but not for mobile browsers.

So in the end I used this

var clipText;
  if (e.originalEvent.clipboardData !== undefined){
    clipText = e.originalEvent.clipboardData.getData('text/plain')
  } else {
    clipText = window.clipboardData.getData('text')
  }



回答4:


$("element").on('paste', function (e)
{
if (window.clipboardData) 
{
pastedText = window.clipboardData.getData('Text')
}
else if (e.clipboardData || e.originalEvent.clipboardData != undefined)
{
pastedText = e.originalEvent.clipboardData.getData('text/plain')
}
}
});


来源:https://stackoverflow.com/questions/30125770/paste-event-listener-on-internet-explorer-getting-wrong-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!