JavaScript get clipboard data on paste event (Cross browser)

前端 未结 20 2370
小蘑菇
小蘑菇 2020-11-21 11:22

How can a web application detect a paste event and retrieve the data to be pasted?

I would like to remove HTML content before the text is pasted into a rich text edi

20条回答
  •  情书的邮戳
    2020-11-21 11:57

    Just let the browser paste as usual in its content editable div and then after the paste swap any span elements used for custom text styles with the text itself. This seems to work okay in internet explorer and the other browsers I tried...

    $('[contenteditable]').on('paste', function (e) {
        setTimeout(function () {
            $(e.target).children('span').each(function () {
                $(this).replaceWith($(this).text());
            });
        }, 0);
    });
    

    This solution assumes that you are running jQuery and that you don't want text formatting in any of your content editable divs.

    The plus side is that it's super simple.

提交回复
热议问题