jQuery粘贴到contenteditable中时,可防止Chrome文本在<div> </div>

时间:2019-09-20 16:16:05

标签: jquery google-chrome contenteditable

该问题仅发生在Google Chrome中,在Firefox中可以正常工作。

没有格式的简单文本:

select its text and paste
Title Example
parrafe

parrafe

parrafe


New Line 
Other Line

当粘贴可编辑的内容时,Chrome浏览器的我的文本粘贴返回:

<div>Title Example
</div><div>parrafe
</div><div>
</div><div>parrafe
</div><div>
</div><div>parrafe
</div><div>
</div><div>
</div><div>New Line 
</div><div>Other Line</div>

如何防止我的文字回卷? Chrome浏览器应设置换行符

我的代码HTML:

<article contenteditable="true">
    Paste Here
</article>
<section>
    <div>
        <span>
            <h1>select its text and paste</h1>
            <h2>Title Example</h2>
            <p>parrafe</p>
            <p>parrafe</p>
            <p>parrafe</p>
            <br/>
            New Line
            <br/>
            Other Line
        </span>
    </div>
</section>

我的jQuery代码:

 $('[contenteditable]').on('paste', function(e) {

        e.preventDefault();

        var text = '';

        if (e.clipboardData || e.originalEvent.clipboardData) {
            text = (e.originalEvent || e).clipboardData.getData('text/plain');
        } else if (window.clipboardData) {
            text = window.clipboardData.getData('Text');
        }
        text = text.replace(/<[^>]*>?/gm, '');

        if (document.queryCommandSupported('insertText')) {
            document.execCommand('insertText', false, text);
        } else {
            document.execCommand('paste', false, text);
        }

    });

$('[contenteditable]').keydown(function(e) {
   if (e.keyCode === 13) {
        document.execCommand('insertHTML', false, '<br><br>');
     return false;
   }
});

我的jsFiddle:

https://jsfiddle.net/qnu47L5a/

0 个答案:

没有答案