如何在CKEditor中移除自定义placeholder元素时触发事件?
CKEditor 5 自定义占位符元素移除触发事件实现方法
1. 用内容变更事件做基础监听
在你的自定义插件的init方法里,给编辑器绑定change:data事件,每次内容变动时对比前后的占位符列表:
- 初始化时先缓存当前所有占位符的标识(比如元素文本或者你给加的
data-id自定义属性) - 每次内容变更时,重新获取当前的占位符列表,和缓存的对比,找出被删掉的项
- 调用你的状态更新函数标记这些项已移除,再更新缓存列表
- 代码示例:
init() { const editor = this.editor; let cachedPlaceholders = this._getCurrentPlaceholders(); editor.model.document.on('change:data', () => { const currentPlaceholders = this._getCurrentPlaceholders(); const removed = cachedPlaceholders.filter(id => !currentPlaceholders.includes(id)); if (removed.length) { // 替换成你的状态更新函数 markPlaceholderAsRemoved(removed); cachedPlaceholders = currentPlaceholders; } }); } // 辅助函数:拿到当前所有占位符的标识 _getCurrentPlaceholders() { const editor = this.editor; const ids = []; editor.model.walker({ shallow: false }).forEach(node => { if (node.is('element') && node.hasClass('placeholder')) { // 这里用文本当标识,也可以换成node.getAttribute('data-id') ids.push(node.getChild(0).data); } }); return ids; }
2. 利用小部件的删除事件(更精准)
如果你的占位符是按照CKEditor官方小部件规范做的(继承了Widget插件),直接监听小部件的delete事件就行:
- 在插件
init方法里,拿到Widget插件实例,绑定事件:
init() { const editor = this.editor; const widgetsPlugin = editor.plugins.get('Widget'); widgetsPlugin.on('delete', (evt, widget) => { if (widget.element.hasClass('placeholder')) { const placeholderId = widget.element.getChild(0).data; // 调用你的状态函数 markPlaceholderAsRemoved([placeholderId]); } }); }
- 前提是你已经通过
widgets.register把占位符元素注册成了小部件,并且编辑器加载了Widget插件。
3. 监听模型节点的移除事件(底层精准方案)
直接监听模型节点的remove事件,不需要依赖小部件插件:
init() { const editor = this.editor; editor.model.document.on('remove', (evt, node) => { if (node.is('element') && node.hasClass('placeholder')) { const placeholderId = node.getChild(0).data; markPlaceholderAsRemoved([placeholderId]); } }); }
这种方式只要你的占位符元素在模型里被正确识别为带placeholder类的元素,就能精准触发。
内容的提问来源于stack exchange,提问作者pranav m
相关产品推荐
相关产品推荐

