使用JavaScript语法高亮显示

时间:2015-10-16 17:21:12

标签: javascript html highlight contenteditable

我试图用JavaScript制作一个简单的语法荧光笔,但我总是遇到同样的问题。该程序的工作原理如下:当用户键入enter(没有shift键)时,程序将用另一个红色替换关键字var(这仍然是基本的)。问题是无论何时按Enter键,文本都会突出显示,但光标会返回第一行的第一个单词。你怎么认为我可以防止这种情况发生?

<div class="container">
    <pre class="text"><code contenteditable="true" id="format">
    </code></pre>
</div>

JS

var editor = document.getElementById('format');
var npatt = / *var +/igm
editor.addEventListener('keyup', highlight);

function highlight(e){
    var content = editor.innerHTML;
    if(e.which === 13 && e.shiftKey===false){
        editor.innerHTML = content.replace(npatt, '<span style="color:red">var</span>&nbsp;');
        console.log(editor.innerHTML);
    }
}

1 个答案:

答案 0 :(得分:2)

可以根据this answer中的方法将光标移动到contenteditable元素的末尾。该方法使用window.getSelection() method来查找光标位置。

我对您的代码进行了一些更改。

  1. 添加test check以查看正则表达式是否与内容匹配,以避免在每次 Enter 击键时调用replace并设置editor.innerHTML作为原始代码那样。
  2. 添加了对cursorManager.setEndOfContenteditable方法的调用(来自上面提到的答案),以便在replace操作后将光标重置为编辑器的末尾。
  3. 这是更新的代码。

    var editor = document.getElementById('format');
    var npatt = / *var +/igm;
    
    editor.addEventListener('keyup', highlight);
    
    function highlight(e){
        var content = editor.innerHTML;
    
        if(e.which === 13 && e.shiftKey === false && npatt.test(content)) {
            editor.innerHTML = content.replace(npatt, '<span style="color:red">var</span>&nbsp;');
            cursorManager.setEndOfContenteditable(editor);
        }
    }
    

    这是一个有效的例子。

    var editor = document.getElementById('format');
    var npatt = / *var +/igm;
    
    editor.addEventListener('keyup', highlight);
    
    function highlight(e){
        var content = editor.innerHTML;
      
        if(e.which === 13 && e.shiftKey === false && npatt.test(content)) {
            editor.innerHTML = content.replace(npatt, '<span style="color:red">var</span>&nbsp;');
            cursorManager.setEndOfContenteditable(editor);
        }
    }
    
    //Code to set the cursor position modified from this answer: https://stackoverflow.com/a/19588665/830125
    //Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
    (function( cursorManager ) {
    
        //From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
        var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
    
        //From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
        Array.prototype.contains = function(obj) {
            var i = this.length;
            while (i--) {
                if (this[i] === obj) {
                    return true;
                }
            }
            return false;
        }
    
        //Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
        function canContainText(node) {
            if(node.nodeType == 1) { //is an element node
                return !voidNodeTags.contains(node.nodeName);
            } else { //is not an element node
                return false;
            }
        };
    
        function getLastChildElement(el){
            var lc = el.lastChild;
            while(lc && lc.nodeType != 1) {
                if(lc.previousSibling)
                    lc = lc.previousSibling;
                else
                    break;
            }
            return lc;
        }
    
        //Based on Nico Burns's answer
        cursorManager.setEndOfContenteditable = function(contentEditableElement)
        {
            var range,selection;
            if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
            {    
                range = document.createRange();//Create a range (a range is a like the selection but invisible)
                range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                selection = window.getSelection();//get the selection object (allows you to change selection)
                selection.removeAllRanges();//remove any selections already made
                selection.addRange(range);//make the range you have just created the visible selection
            }
            else if(document.selection)//IE 8 and lower
            { 
                range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                range.select();//Select the range (make it the visible selection
            }
        }
    
    }( window.cursorManager = window.cursorManager || {}));
    <div class="container">
        <pre class="text"><code contenteditable="true" id="format">
        </code></pre>
    </div>