wangEditor :自定义粘贴内容样式

wangEditor自定义粘贴样式

需求:粘贴文本内容时,不能有原格式,要用系统默认设定格式(格式要求:字体:黑体,22px,行高1.5)

wangEditor 提供了粘贴拦截钩子函数

onPaste 钩子

模板中使用

<template>
  <div>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <!-- 工具栏 -->
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
      />
      <!-- 编辑器 -->
      <Editor
        style="height: 400px; overflow-y: auto"
        :defaultConfig="editorConfig"
        :defaultContent="defaultContent"
        v-model="content"
        @onChange="onChange"
        @onCreated="onCreated"
        @customPaste="customPaste"
      />
    </div>
  </div>
</template>

对粘贴的内容进行处理:

customPaste(editor, event) {
      // 阻止默认粘贴行为(先不急着插入)
      event.preventDefault();
      const pasteStyle = {
        color: "#ff0000",
        fontSize: "22px",
        lineHeight: "1.5",
        fontFamily: "黑体"
      };
      // 获取纯文本或处理后的 HTML
      const clipboardData = event.clipboardData || window.clipboardData;
      const htmlContent = clipboardData.getData("text/html");
      const textContent = clipboardData.getData("text/plain");

      let processedHtml = "";

      if (htmlContent) {
        // 有 HTML 内容时,用 DOMParser 解析并清理样式
        const parser = new DOMParser();
        const doc = parser.parseFromString(htmlContent, "text/html");

        // 遍历所有元素,清除样式并统一设置
        const elements = doc.body.querySelectorAll("*");
        elements.forEach(el => {
          el.style.cssText = ""; // 清除内联样式
          el.removeAttribute("class"); // 清除 class
          el.removeAttribute("style"); // 再次确保

          // 设置统一字体和颜色
          el.style.fontFamily = pasteStyle.fontFamily;
          el.style.lineHeight = pasteStyle.lineHeight;
          el.style.fontSize = pasteStyle.fontSize;
        });

        processedHtml = doc.body.innerHTML;
      } else {
        // 降级为纯文本
        const span = document.createElement("p");
        span.textContent = textContent;
        span.style.fontFamily = pasteStyle.fontFamily;
        span.style.lineHeight = pasteStyle.lineHeight;
        span.style.fontSize = pasteStyle.fontSize;
        processedHtml = span.outerHTML;
      }
      console.log(editor, "editor");

      // 插入处理后的 HTML
      editor.dangerouslyInsertHtml(processedHtml);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值