How to show line numbers for code using JavaScript?

Here is the thing. I am using ' Highlight.js ' (automatic javascript-based syntax syntax) to syntactically highlight code on my website. But it does not support line numbers or zebra striping (for alternative lines of code).

My code block is wrapped in <pre><code>blocks as follows:

<pre><code>
&lt;script type=&quot;text/javascript&quot;&gt;
// Say hello world until the user starts questioning
// the meaningfulness of their existence.
function helloWorld(world) {
for (var i = 42; --i &gt;= 0;) {
alert(&#39;Hello &#39; + String(world));
}
}
&lt;/script&gt;
&lt;style&gt;
p { color: pink }
b { color: blue }
u { color: &quot;umber&quot; }
&lt;/style&gt;
</code></pre>

And the result is as follows:

Syntax Highlighted Code

Now I want to dynamically display line numbers for code using JavaScript. How should I do it? (Also, if possible, how can I show the zebra stripe?)

Thank.

PS: I don’t know JavaScript, so please try to be as clear as possible. I will try my best to understand. Thank.

+5
3

:

  • HTML .
  • (\n).
  • .
  • .
  • HTML .

, , , , . , .

+2

.

, ace.js.

, , , .

, , :

var line = 1;
code = code.replace(/^/gm, function() {
    return '<span class="line-number-position">&#x200b;<span class="line-number">' + line++ + '</span></span>';
});

/^/gm "" span-in-span.

&#x200b; - , , , Firefox , .

line-number-positionand line-numberare CSS classes such as:

.line-number-position {
    position: relative;
    top: 0;
}

.line-number {
    position: absolute;
    text-align: right;
    right: 17px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
    font-size: 12px;
}

Yes, there are some magic numbers to match ace formatting, but the point is to put a relative positional zero size at the beginning of each line and use it as a control point to add an absolute position in the left margin.

Works with current browsers Chrome, Safari, Firefox and Opera.

+2
source

All Articles