Paste rich text into content-editable div and only keep bold and italics formatting

后端 未结 3 1327
礼貌的吻别
礼貌的吻别 2020-12-23 14:35

I want to paste some rich text which has different fonts, font sizes, font weights, etc. into a content-editable div and ONLY keep boldness and italics. Any ide

3条回答
  •  时光取名叫无心
    2020-12-23 15:16

    Here's a working demo: http://jsfiddle.net/SJR3H/7/

    $(document).ready(function(){
    
            $('[contenteditable]').on('paste',function(e) {
    
                e.preventDefault();
    
                var text = (e.originalEvent || e).clipboardData.getData('text/html') || prompt('Paste something..');
                var $result = $('
    ').append($(text)); $(this).html($result.html()); // replace all styles except bold and italic $.each($(this).find("*"), function(idx, val) { var $item = $(val); if ($item.length > 0){ var saveStyle = { 'font-weight': $item.css('font-weight'), 'font-style': $item.css('font-style') }; $item.removeAttr('style') .removeClass() .css(saveStyle); } }); // remove unnecesary tags (if paste from word) $(this).children('style').remove(); $(this).children('meta').remove() $(this).children('link').remove(); }); });

    Later edit: http://jsfiddle.net/SJR3H/8/

    i added the following lines:

    $item.replaceWith(function(){
           return $("", {html: $(this).html()});
    });
    

    It actually replaces all html tags with spans. There you can optionally choose to let some tags as they were in the original text (h1, p, etc), styling them as you desire.

提交回复
热议问题