【问题标题】:Paste rich text into content-editable div and only keep bold and italics formatting将富文本粘贴到内容可编辑的 div 中,并且只保留粗体和斜体格式
【发布时间】:2014-01-21 12:06:09
【问题描述】:

我想将一些具有不同字体、字体大小、字体粗细等的富文本粘贴到内容可编辑的div 中,并且只保留粗体和斜体。知道该怎么做吗?

以下代码在粘贴到内容可编辑的 div 中时将富文本转换为纯文本。

$('[contenteditable]').on('paste',function(e) {
    e.preventDefault();
    var text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Paste something..');
    document.execCommand('insertText', false, text);
});

我试过查看上面代码中的text 变量,但它似乎没有被格式化。

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    这是一个工作演示: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 = $('<div></div>').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();
    
            });
    
        });
    

    稍后编辑: http://jsfiddle.net/SJR3H/8/

    我添加了以下几行:

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

    它实际上用spans 替换了所有html 标签。在那里,您可以选择保留原始文本中的某些标签(h1p 等),根据需要设置它们的样式。

    【讨论】:

    • 嘿克里斯蒂,这在某些情况下似乎不起作用。我尝试复制维基百科文章的一部分(带有

      标签等),格式和底层 html 结构仍然存在。知道如何解决这个问题吗?我不再需要这个了,但从外观上看,它会帮助很多人!

    • 这真的很接近!我认为很多人都可以从这里解决 - 只是上标、链接和其他一些东西仍然存在。谢谢!
    【解决方案2】:

    让我们从您的代码开始:

    //on paste
    var text = (e.originalEvent || e).clipboardData.getData('text/plain')
    
    
    //html in clipboard are saved as Plain Unicode string , 
    
    getData('text/plain') //return data as string,
    
    //if MIME TYPE 'text/html' is used you will get data as html with style attributes
    
    // insert text
    
    document.execCommand('insertText', false, text);
    
    //this will simply insert the text to contenteditable div.
    
    //so there is no chance of knowing recieved text is bold / italics.
    

    (1)我们必须以html的形式获取数据,以获取样式属性:fontWeight,fontStyle。

    (2) 减少 html 所需的样式格式,

    (3) 附加到 contenteditable div。

    !重要::

    我们依靠 Clipboard API 来获取数据。

    较新的浏览器不完全支持,请查看以下链接:

    https://developer.mozilla.org/en-US/docs/Web/Reference/Events/paste

    http://caniuse.com/clipboard

    所以在 IE 浏览器中它不会按预期工作。

    我们在getData()中传入的数据格式参数在IE浏览器中是不同的:

    http://msdn.microsoft.com/en-us/library/ie/ms536436(v=vs.85).aspx

    所以我们只从 getData() 方法得到纯字符串, 我签入了 IE 9.0.8112.16421(未更新),

    我不知道版本 IE 10、11。

    我以某种方式编码, 如果在 ie 10,11 代码中支持 getData("Html"),要求就会完成。

    代码有效: 像 @Cristi 所做的那样,获取所有 html 元素。

    遍历它们,而不是改变样式属性,我们使用标签。

    粗体标签和斜体标签。

    迭代是异步完成的, 因为粘贴大文本内容可能会挂起浏览器。

    我曾在 Chrome、Firefox 中测试过。

    pasteArea.addEventListener('paste', function(e) {
    
        // prevent pasting text by default after event
        e.preventDefault(); 
    
        var clipboardData = {},
        rDataText,
        rDataHTML;
    
        clipboardData = e.clipboardData;
        rDataHTML = clipboardData.getData('text/html');
        rDataPText = clipboardData.getData('text/plain');
    
    
        if (rDataHTML && rDataHTML.trim().length != 0) {
    
            //Function Call to Handle HTML
    
            return false; // prevent returning text in clipboard
        }
    
        if (rDataPText && rDataPText.trim().length != 0) {
    
            //Function Call to Handle Plain String
    
            return false; // prevent returning text in clipboard
        }
    
    }, false);
    
    // Handle Plain Text
    function PlainTextHandler(pText) {
        // Remove Line breaks
        // append to contenteditable div - using range.insertNode()
        // document.execCommand();  had issue in ie9 so i didn't used it 
    }
    
    // Handle HTML
    function formatHtml(elem, complete) {
            var flag_italic = false;
            var flag_weight = false;
            var fontStyle;
            var fontWeight;
    
            if (elem.nodeType == 1) { // only pass html elements
    
                // get style in css 
                var CSSStyle = window.getComputedStyle(elem);
                fontStyle = CSSStyle.fontStyle;
                fontWeight = CSSStyle.fontWeight;
    
                // get style defined by inline
                var InlineStyle = elem.style;
                inlineFontStyle = InlineStyle['font-style'];
                inlineFontWeight = InlineStyle['font-weight'];
                if (inlineFontStyle && inlineFontStyle.trim() != '') fontStyle = inlineFontStyle;
                if (inlineFontWeight && inlineFontWeight.trim() != '') fontWeight = inlineFontWeight;
    
                // get style defined in MSword
                var msStyle = elem.getAttribute('style');
                if (/mso-bidi/.test(msStyle)) {
                    var MSStyleObj = {};
                    var styleStrArr = msStyle.split(";");
                    for (i = 0; i < styleStrArr.length; i++) {
                        var temp = styleStrArr[i].split(":");
                        MSStyleObj[temp[0]] = temp[1];
                    }
                    fontStyle = MSStyleObj['mso-bidi-font-style'];
                    fontWeight = MSStyleObj['mso-bidi-font-weight'];
                }
    
                if (fontStyle && fontStyle == 'italic') flag_italic = true; // flag true if italic
    
                if (fontWeight && (fontWeight == 'bold' || 600 <= (+fontWeight))) flag_weight = true;  // flag true if bold - 600 is semi bold
    
                // bold & italic are not applied via style
                // these styles are applied by appending contents in new tags string & bold
                if (flag_italic && flag_weight) {
                    var strong = document.createElement('strong');
                    var italic = document.createElement('i');
                    strong.appendChild(italic);
                    newtag = strong;
                } else {
                    if (flag_italic) {
                        newtag = document.createElement('i');
                    } else if (flag_weight) {
                        newtag = document.createElement('strong');
                    } else {
                        // remove un wanted attributes & element
                        var tagName = elem.tagName;
                        // strong are not skipped because, by creating new unwanted attributes will be removed
                        if (tagName == 'STRONG' || tagName == 'B') {
                            newtag = document.createElement('strong');
                        } else if (tagName == 'I') {
                            newtag = document.createElement('i');
                        } else {
                            newtag = document.createElement('span');
                        }
                    }
                }
    
                // content appended
                var elemHTML = elem.innerHTML;
                if (flag_italic && flag_weight) {
                    newtag.childNodes[0].innerHTML = elemHTML;
                } else {
                    newtag.innerHTML = elemHTML;
                }
    
                // curr element is replaced by new
                elem.parentNode.insertBefore(newtag, elem);
                elem.parentNode.removeChild(elem);
            }
            complete() // completed one iteration
        }
    

    小提琴: http://jsfiddle.net/aslancods/d9cfF/7/

    【讨论】:

      【解决方案3】:

      我在我的网站上使用了很长时间

      $(document).on('paste','#tesc', function() {
                       setTimeout(function() {
                              asd = strip_tags( $('#tesc').html(), '<b><b/><i></i>');
      
                              $('#tesc').html( asd );
                      },100);
      
              });
      
      function strip_tags (input, allowed) {
          /* http://kevin.vanzonneveld.net*/
      
          if ( input == undefined ) { return ''; }
      
          allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
          var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
              commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
          return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
              return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-11
        • 1970-01-01
        • 2016-01-02
        • 1970-01-01
        • 2015-07-02
        • 1970-01-01
        • 2011-07-25
        相关资源
        最近更新 更多