使用Highlight.js插件时如何在飞行中应用样式?

时间:2017-04-19 17:20:11

标签: javascript html css syntax-highlighting

我正在研究一些我需要在飞行中触发事件并应用高光样式的代码。由于某种原因,样式没有得到应用。

https://jsfiddle.net/qm9rgh0u/

hljs.initHighlightingOnLoad();

var content_div = document.getElementById("edit");

content_div.addEventListener("keypress", function() {
  hljs.initHighlightingOnLoad();

})
@import url('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/styles/default.min.css');
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/highlight.min.js"></script>

<div id="edit" contenteditable="true">
  <pre>
<code>
    var i = 0,
        colors = ["red","blue","green"];
    var content = document.getElementById("text");
    function appendFunction(e,id){

      var new_span = document.createElement("span");
      new_span.style.color = colors[i];
      new_span.textContent = id.textContent;
      id.append(new_span);
      // var new_span = "<span style=color:'+colors[i]+'>"+id.textContent+"</span>";
      // var
      // id.append(new_span);
    }



      var id = document.getElementById("text");
      id.addEventListener("keyup", function(event){
        appendFunction(event,id);
      })



</code>
</pre>
</div>

1 个答案:

答案 0 :(得分:1)

我在您的html id="codeblock"代码

中添加了<code>

同样使用更新的js,我将按键更改为模糊,以便您可以更新代码,当您失去焦点时,您将获得更新的样式:

hljs.initHighlightingOnLoad();

var content_div = document.getElementById("edit");
content_div.addEventListener("blur", function() {
  hljs.highlightBlock(document.getElementById("codeblock"));
})

https://jsfiddle.net/dalinhuang/r2a56w9b/