使用HTML标签属性contenteditable,用js处理复制粘贴时样式

1,930 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

在开发过程中,可能会出现使用 html标签divbody 的可编辑状态的时候,设置其属性为contenteditable="true",很多的编辑器也是使用此属性。比如 百度的UEditor编辑器WangEditor等都能看到contenteditable的身影。

不过在使用此属性时,也不可避免出现复制粘贴的情况。如果有特殊需求,复制粘贴只需要文本和换行,不需要样式。那么这就需要做单独处理。

举例:

界面中有这样一个div:

<div contenteditable="true" id="" class="div_content symptom-textarea" placeholder="" maxlength="1000"></div>

从网络上复制一段文字: 地址:baike.baidu.com/item/www/20…

需要复制的地方文字如图所示:

image.png

不做任何处理复制粘贴后的结果,如图:

image.png

html代码:

<div contenteditable="true" id="" class="div_content symptom-textarea" placeholder="" maxlength="1000">
    <div class="authorityListPrompt" style="margin: 15px 0px; color: rgb(51, 51, 51); font-family: &quot;Helvetica Neue&quot;, Helvetica, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">
            <div class="main-content-zj" style="color: rgb(102, 102, 102); background: url(&quot;https://bkssl.bdimg.com/static/wiki-lemma/widget/basicElement/authority/authorityListPrompt/resource/img/authority_f9093fa.png&quot;) left center no-repeat transparent; padding-left: 20px;">
            本词条由<a href="https://baike.baidu.com/science" target="_blank" class="nslog:7175" style="color: rgb(19, 110, 194);">“科普中国”科学百科词条编写与应用工作项目</a>&nbsp;审核 。
            </div>
     </div>
     <div class="lemma-summary" label-module="lemmaSummary" style="clear: both; font-size: 14px; color: rgb(51, 51, 51); margin-bottom: 15px; text-indent: 2em; line-height: 24px; zoom: 1; font-family: &quot;Helvetica Neue&quot;, Helvetica, Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; background-color: rgb(255, 255, 255);">
        <div class="para" label-module="para" data-pid="1" style="font-size: 14px; margin-bottom: 15px; text-indent: 2em; line-height: 24px; zoom: 1;">
            WWW是覆盖全球的客户机/服务器网络;当用互联网接入WWW时,用户的计算机就等于一台客户机;通过WWW用户能够和各种不同类型的计算机之间实现有效的通讯。
            <span class="sup--normal" data-sup="1" data-ctrmap=":1," style="line-height: 0; position: relative; vertical-align: baseline; top: -0.5em; white-space: nowrap; margin-left: 2px; color: rgb(51, 102, 204); cursor: pointer; padding: 0px 2px;">&nbsp;[1]</span>
            <a class="sup-anchor" name="ref_[1]_20904215" style="color: rgb(19, 110, 194); position: relative; top: -50px; font-size: 0px; line-height: 0;">&nbsp;</a>
        </div>
    </div>
</div>

不难发现,这样会把所有的样式(包括图片)都会复制进来。

现在如果要去掉不必要的样式,就需要单独处理。

直接上代码:

1、封装一个方法

/**
 * 复制粘贴处理
 * @param e
 */
function textInit(e) {
  e.preventDefault();
  // console.log('粘贴')
  var text;
  var clp = (e.originalEvent || e).clipboardData;
  if (clp === undefined || clp === null) {
    text = window.clipboardData.getData("text") || "";
    if (text !== "") {
      text = text.replace(/(\r\n|\r|\n)/g, '\n')
      // 去除空
      let text_arr = text.split('\n');
      text_arr = text_arr.filter(function(e){return e});
      let new_text = text_arr.join("\n");

      if (window.getSelection) {
        var newNode = document.createElement("span");
        newNode.innerHTML = new_text;
        window.getSelection().getRangeAt(0).insertNode(newNode);
      } else {
        document.selection.createRange().pasteHTML(new_text);
      }
    }
  } else {
    text = clp.getData('text/plain') || "";
    if (text !== "") {
      text = text.replace(/(\r\n|\r|\n)/g, '\n');

      // 去除空
      let text_arr = text.split('\n');
      text_arr = text_arr.filter(function(e){return e});
      let new_text = text_arr.join("\n");
      // console.log('粘贴:'+new_text)
      document.execCommand('insertText', false, new_text);
    }
  }
}

2、应用上面的方法

这一部分可以自由调取。

注:paste事件
paste: 在发生粘贴操作时触发。
绑定的元素不一定是input,普通的div也是可以绑定的,如果是给document绑定了,就相当于全局了,任何时候的粘贴操作都会触发。

$("body").on("paste",'.div_content', function (e) {
  textInit(e)
});

再次复制粘贴相同文本,结果如下:

image.png

html代码:

<div contenteditable="true" id="" class="div_content symptom-textarea" placeholder="" maxlength="1000">本词条由“科普中国”科学百科词条编写与应用工作项目 审核 。<div>WWW是覆盖全球的客户机/服务器网络;当用互联网接入WWW时,用户的计算机就等于一台客户机;通过WWW用户能够和各种不同类型的计算机之间实现有效的通讯。 [1]&nbsp;</div></div>

是不是一下子清爽了很多。

如果还有特殊需求,就在封装的方法中做特殊处理即可。



END

如有问题请在下方留言。

或关注我的公众号“孙三苗”(sunsanmiao),输入“联系方式”。获得进一步帮助。