Monaco Editor hoverMessage不显示:WebComponent阴影DOM下无悬浮错误提示
问题原因
该问题根源是Monaco Editor的悬浮类部件默认挂载到全局document.body,和你运行的Web Component Shadow DOM属于隔离的DOM树,导致两个问题:
- Monaco无法捕获Shadow DOM内的鼠标悬停事件,触发不了提示渲染逻辑
- 就算生成了悬浮节点,也不会插入到编辑器内部的
overflowingContentWidgets容器,无法正常展示
修复步骤
1. 补充编辑器挂载配置
创建编辑器时显式指定3项核心配置,适配Shadow DOM运行环境:
firstUpdated() { let mbDomNode = document.querySelector("#code-area"); let codeArea = mbDomNode ? (mbDomNode as HTMLElement) : undefined; this.editor = monaco.editor.create(this.container.value!, { value: this.getCode(), language: this.getLang(), theme: this.getTheme(), automaticLayout: true, minimap: { enabled: false, }, ariaContainerElement: codeArea, glyphMargin: true, // 新增适配配置开始 hover: { enabled: true // 显式开启悬停提示,避免默认配置被覆盖 }, // 指定悬浮部件挂载到Shadow DOM内的容器,直接用编辑器父容器即可 overflowWidgetsDomNode: this.container.value!, fixedOverflowWidgets: true, // 避免提示被父容器的overflow属性裁剪 // 新增适配配置结束 }); monaco.languages.register({ id: "mix" }); monaco.languages.setMonarchTokensProvider("mix", mixLang); }
2. 调整装饰器触发范围
你当前只配置了linesDecorationsClassName的悬停消息,触发区域只有行号和代码之间的窄条区域。如果需要整行悬停都能触发提示,打开注释掉的className配置即可,这个类会应用到代码行本身,覆盖整行触发区域:
addError(err: { row: number; message: string }) { this.editor!.deltaDecorations( [], [ { range: new monaco.Range(err.row, 1, err.row, 30), options: { isWholeLine: true, className: "error-decoration", // 打开该配置,整行代码都可触发悬停 linesDecorationsClassName: "error-decoration", hoverMessage: { value: err.message }, }, }, ] ); }
补充优化点:如果需要多次调用
addError添加多个错误,不要每次第一个参数都传空数组,建议把deltaDecorations返回的装饰ID数组存储起来,下次调用时作为第一个参数传入,避免旧装饰重复叠加。
内容的提问来源于stack exchange,提问作者Simon H
相关产品推荐
相关产品推荐

