如何阻止Tiptap插入链接后出现链接自动传播现象?
解决Tiptap插入链接后输入内容自动继承链接格式的问题
方法一:自定义插入链接命令,完成后自动移出光标
默认的setLink命令会让光标停留在链接节点内部,后续输入会自动继承链接格式。可以自定义命令,在设置链接后将光标移到链接外部:
// 初始化编辑器 const editor = new Editor({ extensions: [ Link.configure({ // 保留你的原有配置,比如 openOnClick、target 等 }) ], content: '<p>编辑内容</p>' }) // 注册自定义插入链接命令 editor.commands.register('insertLinkAndEscape', ({ href, text }) => { return editor.chain() .focus() .setLink({ href }) // 为选中内容设置链接 .insertContent('') // 插入空内容,将光标移至链接外部 .run() }) // 使用自定义命令代替默认的 setLink // 示例:选中文本后调用 editor.commands.insertLinkAndEscape({ href: 'https://example.com', text: '示例链接' })
方法二:监听光标位置,自动跳出链接节点
通过监听编辑器的update事件,判断光标是否处于链接节点末尾,若则自动将光标移至外部:
editor.on('update', () => { const { selection } = editor.state const $pos = selection.$from // 检查光标是否位于段落末尾的链接节点后 if ($pos.parent.type.name === 'paragraph' && $pos.pos === $pos.parent.end() - 1) { const lastNode = $pos.parent.child($pos.parent.childCount - 1) const hasLinkMark = lastNode.marks.some(mark => mark.type.name === 'link') if (hasLinkMark) { // 将光标移至链接节点外部 editor.commands.focus($pos.pos + 1) } } })
方法三:插入链接后拆分区块
如果希望在链接后直接开启新的无链接段落,可以在设置链接后调用splitBlock命令:
editor.chain() .focus() .setLink({ href: 'https://example.com' }) .splitBlock() // 拆分出全新的段落,光标位于新段落中 .run()
内容的提问来源于stack exchange,提问作者BingeCode
相关产品推荐
相关产品推荐

