基于Tiptap 2.2.2构建含固定<author>标签的自定义blockquote扩展
实现带固定标签的Tiptap Blockquote(2.2.2版本)
针对你的需求,以下是纯JS实现方案,适配Tiptap 2.2.2版本:
1. 注册自定义节点
首先需要让Tiptap识别自定义的<author>标签,定义一个节点扩展:
const AuthorNode = { name: 'author', group: 'block', content: 'text*', // 允许编辑文本内容 parseHTML() { return [{ tag: 'author' }]; }, renderHTML() { return ['author', 0]; }, // 可选:添加快捷键,比如在author内回车创建新段落 addKeyboardShortcuts() { return { 'Enter': () => { this.editor.commands.insertContent('<p></p>'); return true; } }; } };
2. 自定义Blockquote扩展
修改默认的blockquote行为,确保点击按钮时自动在末尾插入<author>标签:
const CustomBlockquote = { name: 'blockquote', extend: '@tiptap/extension-blockquote', addCommands() { return { toggleCustomBlockquote: () => ({ commands, state, editor }) => { const isActive = commands.isActive('blockquote'); if (isActive) { // 取消blockquote格式 return commands.toggleBlockquote(); } else { // 包裹选中内容为blockquote,然后插入author节点 return commands.wrapIn('blockquote') .then(() => { // 定位到blockquote末尾位置 const blockquotePos = state.doc.content.findIndex(node => node.type.name === 'blockquote'); const blockquoteNode = state.doc.content.child(blockquotePos); const insertPos = blockquotePos + blockquoteNode.nodeSize; // 插入带默认提示文本的author节点 const authorNode = editor.schema.nodes.author.create({}, editor.schema.text('Please type the author')); const tr = state.tr.insert(insertPos - 1, authorNode); // 调整位置确保插入到blockquote内部末尾 editor.view.dispatch(tr); return true; }); } } }; } };
3. 初始化编辑器
将自定义扩展加入编辑器配置:
import { Editor } from '@tiptap/core'; import StarterKit from '@tiptap/starter-kit'; const editor = new Editor({ element: document.querySelector('#your-editor-element'), extensions: [ StarterKit, AuthorNode, CustomBlockquote ], // 可选:初始内容 content: '<p>This is a quote</p><p>This is a quote</p>' });
4. 绑定工具栏按钮
给blockquote按钮绑定自定义命令:
document.querySelector('#toggle-blockquote-btn').addEventListener('click', () => { editor.commands.toggleCustomBlockquote(); });
关键说明
- 所有内容(包括
<author>内的文本)均可直接编辑,符合你的需求; - 无论选中已有内容还是空白段落,点击按钮都会自动生成带
<author>标签的blockquote; - 适配Tiptap 2.2.2版本的扩展语法,避免版本兼容问题。
内容的提问来源于stack exchange,提问作者minh chanh le
相关产品推荐
相关产品推荐

