需求:粘贴文本内容时,不能有原格式,要用系统默认设定格式(格式要求:字体:黑体,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);
}
wangEditor自定义粘贴样式
2107

被折叠的 条评论
为什么被折叠?



