Vue开发Lexical富文本编辑器:ListItemNode内联样式实现咨询
解决Lexical Playground列表项内联样式的实现方式
lexical-playground里的<li>内联样式是通过扩展默认ListItemNode的DOM生成逻辑+给列表项节点添加格式属性实现的,不需要完全自定义ListItemNode,具体实现逻辑如下:
扩展ListItemNode的DOM生成逻辑
利用Lexical的extendNodeAPI,在默认ListItemNode的createDOM方法中加入样式转换逻辑:读取节点存储的格式属性(比如字体大小、颜色),将其转换成内联样式绑定到<li>元素上。
示例代码:import { ListItemNode } from '@lexical/list'; ListItemNode.extend({ createDOM(config) { const dom = super.createDOM(config); const itemFormat = this.getFormat(); // 根据格式属性添加内联样式 if (itemFormat.fontSize) { dom.style.fontSize = `${itemFormat.fontSize}px`; } if (itemFormat.color) { dom.style.color = itemFormat.color; } // 可扩展更多样式属性,比如 fontWeight、fontStyle 等 return dom; }, });给ListItemNode写入样式格式
当用户通过工具栏操作(比如设置字体大小、颜色)时,通过编辑器的update方法,将样式属性写入选中的ListItemNode的format中:
示例代码:const applyListItemStyle = (editor, styleKey, value) => { editor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { // 获取选中范围内的所有列表项节点 const selectedNodes = $getNodesInRange(selection).filter( node => node.getType() === 'listitem' ); selectedNodes.forEach(node => { node.setFormat({ ...node.getFormat(), [styleKey]: value, }); }); } }); };整合工具栏交互
playground的工具栏会监听选中状态,当检测到选中的是列表项时,将样式操作绑定到上述方法,从而实现点击工具栏按钮后,自动给<li>添加对应内联样式。
这种方式只是在默认ListItemNode的基础上扩展行为,不需要完全重写自定义节点,刚好符合你不想自定义ListItemNode的需求。
内容的提问来源于stack exchange,提问作者Vatchi
相关产品推荐
相关产品推荐

