Codemirror中悬停Interpolation节点时能否修改光标样式?
在CodeMirror中悬停特定节点时更改光标样式
完全可行,核心思路是通过监听鼠标位置匹配目标节点范围,动态修改编辑器的光标样式,具体实现步骤如下:
- 定位目标节点范围:借助CodeMirror的语法分析能力,通过
getTokenAt或自定义AST解析逻辑,判断鼠标当前位置是否落在Interpolation节点的起止区间内。如果是自定义语法模式,确保你的模式已经给Interpolation节点标记了对应的类型(比如token类型设为interpolation)。 - 监听鼠标移动事件:给编辑器的外层容器绑定
mousemove事件,实时获取鼠标对应的文档坐标位置。 - 切换光标样式:当检测到鼠标悬停在
Interpolation节点上时,修改编辑器容器的cursorCSS属性;离开节点范围时恢复默认样式。
示例代码:
// 初始化编辑器 const editor = CodeMirror.fromTextArea(document.getElementById('editor'), { lineNumbers: true, mode: 'your-custom-syntax-mode' // 替换为你的自定义语法模式 }); // 监听鼠标移动 editor.getWrapperElement().addEventListener('mousemove', (e) => { // 获取鼠标对应的文档位置 const docPos = editor.coordsChar({ left: e.clientX, top: e.clientY }); // 获取当前位置的token信息 const currentToken = editor.getTokenAt(docPos); // 判断是否为Interpolation节点 if (currentToken?.type === 'interpolation') { editor.getWrapperElement().style.cursor = 'help'; // 替换为你需要的光标样式,比如pointer、text等 } else { // 恢复默认光标 editor.getWrapperElement().style.cursor = ''; } });
如果Interpolation是跨多个token的AST节点,需要额外通过语法树遍历,获取节点的起始和结束位置(行号、列号),再判断鼠标位置是否处于该区间内。
内容的提问来源于stack exchange,提问作者Jonathan R
相关产品推荐
相关产品推荐

