在 tiptap 中,`state.doc.textbetween()` 仅返回纯文本,无法保留自定义节点(如 `
Tiptap 基于 ProseMirror 构建,其核心设计原则是将编辑器文档模型(Node/Mark 树)与浏览器 DOM 严格分离——这意味着 editor.state.doc 中存储的是结构化的 JSON 表示,而非 HTML 字符串;textBetween() 等方法仅面向逻辑文本内容,天然剥离所有节点语义和标记。
因此,若需获取用户当前光标选区的带格式、含自定义标签的 HTML 字符串(例如
const getSelectedHTML = () => {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return '';
const range = selection.getRangeAt(0);
const fragment = range.cloneContents(); // 克隆选区 DOM 片段(保留所有节点、属性、自定义标签)
// 创建临时容器序列化为 HTML
const div = document.createElement('div');
div.appendChild(fragment);
return div.innerHTML;
};
// 在事件中调用(如按钮点击或快捷键)
const handleGetSelection = () => {
const html = getSelectedHTML();
console.log(html); // ✅ 输出: "This shop has 100 customers every day"
};Tiptap 提供 editor.state.doc.slice() + editor.storage.html.serialize()(需启用 @tiptap/extension-html)可导出选区为 HTML;但更推荐使用 editor.state.doc.n
odesBetween() 配合自定义序列化逻辑,以精准控制节点映射规则。
总之,不要试图从 ProseMirror 文档树“反向生成 HTML”——它不是为该目的设计的。拥抱 DOM,用 getSelection() + cloneContents() 是简洁、可靠且符合 Web 标准的解决方案。
立即学习“前端免费学习笔记(深入)”;