如何在javascript实时语法高亮显示中修复反向文本?

时间:2018-06-17 23:41:31

标签: javascript html css text innerhtml

我的脚本会突出显示关键字,但无论何时发生,它都会与字符串混淆并随机处理文本,如反转它并将其混合起来。我想知道是否有人可以告诉我如何解除此文本或移动光标到了满足感的div的最后,或者最多只是为我解决它。我不想要任何外部库只是javascript和jquery。

jsfiddle

JS代码:

function UnColor() {
    var elem = document.getElementById("editor");
    var text = elem.textContent;
    elem.innerHTML = text;
}

function Color() {
    UnColor();
    var elem = document.getElementById("editor");
    var code = elem.innerHTML;
    code = code.replace("var","<span style='color:dodgerblue'>var</span>");
    code = code.replace(/"(.*?)"/g,"<span style='color:green'>&quot;$1&quot;</span>");
    code = code.replace(/&lt;(.*?)&gt;/g,"<span style='color:#F90'>&lt;$1&gt;</span>");
    elem.innerHTML = code;
}

setInterval(Color,1000)

谢谢!

2 个答案:

答案 0 :(得分:0)

如果您遇到的问题是光标在编辑时移动,您可以通过抓住光标的位置并将其放回功能的末尾来解决这个问题。通过获取编辑器文本框的selectionStart属性,然后在运行替换后将selectionEnd属性设置为该值来执行此操作。

查看this answer以获取有关selectionStart和selectionEnd的更多信息。

这是来自this answer的简单代码段,可以让您滚动。

&#13;
&#13;
document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
      position = target.selectionStart; // Capture initial position
  
  target.value = target.value.replace(/\s/g, '');  // This triggers the cursor to move.
  
  target.selectionEnd = position;    // Set the cursor back to the initial position.
});
&#13;
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
<input type="text" id="target" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这个问题随着编辑器id的textContent等同于它的innerHTML而出现。所以改变变量名称就像我在这里写的JS代码一样:

function UnColor() {
    var elem = document.getElementById("editor");
    var text = elem.textContent;
    var elem2;
    elem2.innerHTML = text;
}

function Color() {
    UnColor();
    var elem = document.getElementById("editor");
    var code = elem.innerHTML;
    code = code.replace("var","<span style='color:dodgerblue'>var</span>");
    code = code.replace(/"(.*?)"/g,"<span style='color:green'>&quot;$1&quot;</span>");
    code = code.replace(/&lt;(.*?)&gt;/g,"<span style='color:#F90'>&lt;$1&gt;</span>");
    var elem2;
    elem2.innerHTML = code;
}

setInterval(Color,1000)
相关问题