如何在Tiptap编辑器中为用户提供预加载文本建议并支持快捷保存?
实现Tiptap编辑器点击触发预加载文本建议及快捷键保存功能
1. 绑定编辑器聚焦事件,触发预加载建议
当用户点击Tiptap编辑器触发聚焦时,渲染预加载的文本建议面板,可通过Tiptap内置的onFocus钩子实现:
import { Editor } from '@tiptap/core' import StarterKit from '@tiptap/starter-kit' // 初始化编辑器 const editor = new Editor({ element: document.querySelector('#tiptap-editor'), extensions: [StarterKit], onFocus: () => { renderSuggestionPanel('这是预加载的文本建议内容') } }) // 渲染建议面板的函数 function renderSuggestionPanel(suggestionText) { // 先移除已存在的面板 const existingPanel = document.querySelector('.tiptap-suggestion') if (existingPanel) existingPanel.remove() // 创建新的建议面板 const panel = document.createElement('div') panel.className = 'tiptap-suggestion' panel.textContent = suggestionText // 将面板插入到编辑器容器前,可根据布局调整位置 editor.options.element.parentNode.insertBefore(panel, editor.options.element) }
2. 监听键盘快捷键,确认建议并保存
监听编辑器的键盘事件,当用户按下回车键或右箭头键时,将建议文本插入编辑器并提交到数据库:
// 给编辑器绑定键盘事件 editor.options.element.addEventListener('keydown', (e) => { const suggestionPanel = document.querySelector('.tiptap-suggestion') if (!suggestionPanel) return // 匹配目标按键 if (e.key === 'Enter' || e.key === 'ArrowRight') { e.preventDefault() // 阻止默认行为(如回车换行) // 插入建议文本到编辑器 const suggestionText = suggestionPanel.textContent editor.commands.insertContent(suggestionText) // 移除建议面板 suggestionPanel.remove() // 提交到数据库 saveContentToDB(suggestionText) } }) // 数据库保存逻辑示例 async function saveContentToDB(content) { try { const response = await fetch('/api/save-editor-content', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ content }) }) if (!response.ok) throw new Error('保存失败') // 保存成功后的提示或后续操作 } catch (err) { console.error('数据库保存出错:', err) } }
3. 建议面板样式优化(可选)
添加基础样式让建议面板更贴合产品风格:
.tiptap-suggestion { position: relative; background: #f5f5f5; border: 1px solid #e0e0e0; border-radius: 4px; padding: 10px 16px; margin-bottom: 8px; font-size: 14px; color: #333; }
内容的提问来源于stack exchange,提问作者Faisal Usman
相关产品推荐
相关产品推荐

