WYSIWYG Web组件两大问题求助:函数调用与跨编辑器修改
解决WYSIWYG Web组件的两个问题
问题1:点击工具栏按钮无法调用UpdateActiveStatus函数
报错Uncaught TypeError: this.UpdateActiveStatus is not a function,原因是匿名function回调里的this指向触发点击的按钮元素,而非组件实例。
修复方案
有两种常用解决方式:
- 使用箭头函数:箭头函数会继承外层作用域的
this(即组件实例) - 使用
bind(this)绑定上下文
方式1:箭头函数示例
// Bold menu this.shadowRoot.querySelector('#boldButton').addEventListener('click', () => { document.execCommand('bold'); this.UpdateActiveStatus(); });
方式2:bind绑定示例
// Bold menu this.shadowRoot.querySelector('#boldButton').addEventListener('click', function () { document.execCommand('bold'); this.UpdateActiveStatus(); }.bind(this));
问题2:多个编辑器之间的格式修改干扰
选中第一个编辑器文本后,点击第二个编辑器的工具栏按钮会修改第一个编辑器内容,因为document.execCommand作用于全局选区,而当前选区仍停留在第一个编辑器内。
修复方案
点击工具栏按钮时,先将焦点切换到当前组件的编辑器容器,确保命令作用于当前编辑器。如果需要保留选区,可先保存全局选区,切换焦点后恢复到当前编辑器内。以Bold按钮为例:
this.shadowRoot.querySelector('#boldButton').addEventListener('click', () => { const editor = this.shadowRoot.querySelector('#editorContainer'); // 保存当前全局选区 const selection = document.getSelection(); const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null; // 将焦点切换到当前编辑器 editor.focus(); // 恢复之前的选区(可选,根据需求调整) if (range) { selection.removeAllRanges(); selection.addRange(range); } // 执行格式命令 document.execCommand('bold'); // 更新按钮激活状态 this.UpdateActiveStatus(); });
内容的提问来源于stack exchange,提问作者pitaridis
相关产品推荐
相关产品推荐

