【问题标题】:Syntax highlight with JavaScriptJavaScript 语法高亮
【发布时间】:2015-10-17 02:26:39
【问题描述】:

我正在尝试使用 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);
    }
}

【问题讨论】:

  • 可能光标移动是因为现有内容被语法高亮内容完全替换,所以光标位置无意义,重置为默认位置?
  • 你能发一个 JSfiddle 或一个 sn-p 吗?
  • 是的,但是我该如何解决这个问题?,我的意思是当我点击输入时,替换的文本应该在第一行(或任何行),光标在下一行?

标签: javascript html highlight contenteditable


【解决方案1】:

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

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

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

这是更新后的代码。

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>

【讨论】:

  • 谢谢谢谢谢谢!!,你救了我的命,没想到能做到!谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 2010-10-15
  • 1970-01-01
相关资源
最近更新 更多