可编辑<code> tag using highlight.js? Highlighting code &#34;on the go&#34; as you write it?

时间:2017-05-16 09:14:08

标签: jquery highlight contenteditable live highlight.js

I'm quite new to all this stuff, currently I'm trying to highlight code as I write it. I'm using highlight.js, which is working just fine and styles all the code when I (re)load the site.

My problem comes when I write new code and it's not saved yet - those of you who are familiar with the library know what I'm talking about (I read the documentation a several times and I didn't find anything about live highlighting?)

So I replace my tag on every keyup event inside it. This works fine and highlights, the problem is that my cursor always jumps to the beginning of the . Which is very user-enemy, if you want to keep writing your code and your cursor always jumps to the beginning.

I found some solutions on how to find cursor position in a textarea, but that doesn't work for me. I need to know the cursor position before the keyup event and when it happens, the replace function is called and I need to place my cursor in the same exact position.

Is there any way to do it? Can anybody advise me please?

/**
 * inits highlight.js upon changing the code
 */
$(document).on('keyup', '.js-grid__code-val code', function () {
    $('.js-grid__code-val code').each(function (i, block) {
        hljs.highlightBlock(block);
    });
});
<div class="grid__code-val js-grid__code-val">
  <pre>
    <code class="hljs" contenteditable=""></code>
  </pre>
</div>

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,this solution using rangy为我工作。

Download rangy并在您的项目中导入:

<script src="rangy/rangy-core.min.js"></script>
<script src="rangy/rangy-textrange.min.js"></script>
<script src="rangy/rangy-selectionsaverestore.min.js"></script>

<div class="grid__code-val js-grid__code-val">
    <pre>
        <code class="hljs" contenteditable=""></code>
    </pre>
</div>

<script>
     function highlightBlock(el) {
            let savedSel = rangy.saveSelection();
            hljs.highlightBlock(el);
            rangy.restoreSelection(savedSel);
    }
</script>
/**
 * inits highlight.js upon changing the code
 */
$(document).on('keyup', '.js-grid__code-val code', function () {
    $('.js-grid__code-val code').each(function (i, block) {
        highlightBlock(block);
    });
});