在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