在vue中使用CodeMirror创建XML编辑器经验总结(二)


  接上篇,本篇介绍变量跳转,代码字体放大缩小,鼠标划过添加下划线功能。

  5)变量定义跳转

  实现变量跳转功能,我这里是和后端一起合作完成的,后端伙伴把变量的位置返回给我,当用户选中一个变量的使用时候,点击F12或者右键菜单会跳转到定义处。若做到用户鼠标点在代码上不用选中点右键菜单就能跳转,需要用户点击的时候就获取到用户点击的区域的文本,在源代码中找到了wordAt这个方法,并按照需求进行了改造实现了获取到了需要的结果。

// 此方法为源码中自带的焦点放在一个单词中间,就能返回此时该焦点所在文本的位置信息和文本本身,大家可以根据自己的特殊需要做一些改造
function wordAt(cm, pos) {
    var start = pos.ch, end = start, line = cm.getLine(pos.line);
    while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
    while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
    return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
  }

 

 1 this.editor = CodeMirror.fromTextArea(this.$refs.code, {
 2     extraKeys: {
 3         "F12": function() { // 跳转自定义变量
 4             that.goToDefinition()
 5         }
 6     }
 7 }
 8 goToDefinition(word) { 
 9     if (!word) {
10         this.selectWord = this.editor.getSelection();
11     }
12     if (this.selectWord == "" || this.selectWord.indexOf("#") == -1) {
13         message("请选择自定义变量") return false;
14     } else if (this.defineVarList.length == 0) {
15         message("无自定义变量") return false;
16     }
17 
18     let defined = null 
this.defineVarList.forEach(item = >{ 19 if (item.key == this.selectWord.substring(1)) { 20 defined = item 21 } 22 }) if (defined == null) { 23 message("请选择自定义变量") return false; 24 } 25 let scrollNum = 0 26 if (defined.from.line <= 20) { 27 scrollNum = 0 28 } else { 29 scrollNum = defined.from.line - 15 30 } 31 32 this.editor.focus(); 33 this.editor.setCursor(defined.from); 34 this.editor.setSelection(defined.from, defined.to); 35 this.editor.scrollIntoView({ 36 line: scrollNum, 37 ch: 0 38 }) 39 }

  6)代码字体方法缩小

  在codemirror编辑器外边套一层div,动态设置字号就可以了

<div :style="{fontSize:`${editorFontSize}px`}">
        <textarea ref="code"></textarea>
</div>

  7)鼠标划过添加下划线

  按住ctrl键时,鼠标划过编辑器中的标签、属性、属性值添加下划线,此功能我用到的api是markText

 

var wrapperElement = this.editor.getWrapperElement();
// 监听鼠标划过,ctr按下时,鼠标划过添加下划线
wrapperElement.addEventListener('mousemove', function (e) {
       if (!that.ctrlKeyPressed) {
            return false;
       }
       let y = e.target.getBoundingClientRect().top;
       let pos = that.editor.coordsChar({ left: e.clientX, top: y }, 
 "page");
       let token = that.editor.wordAt(that.editor, pos)
       that.clearTextMarker()
       that.editor.markText(token.from, token.to, { className: "style-mouseover" });
});
// 清空指定的TextMarker对象
clearTextMarker() {
            let marks = this.editor.getAllMarks()
            if (!marks.length) return false;
            for (let i = 0; i < marks.length; i++) {
                if (marks[i].className == "style-mouseover") {
                    marks[i].clear()
                }
            }
        }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM