javascript 如何在 Google Prettify 中为所有行添加行号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8399547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:19:24  来源:igfitidea点击:

How to add line numbers to all lines in Google Prettify?

javascriptcssprettify

提问by aurel

I am using prettify:

我正在使用美化:

<pre class="prettyprint linenums">
  some code
</pre>

It works but the line number show every 5 lines and not for every line. I am using these files

它有效,但行号每 5 行显示一次,而不是每行显示一次。我正在使用这些文件

<link href="../src/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../src/prettify.js"></script>

Basically at the end of this page http://google-code-prettify.googlecode.com/svn/trunk/styles/index.htmlyou can see that I want, but I looked at that code and I can't figure it out.

基本上在这个页面的末尾http://google-code-prettify.googlecode.com/svn/trunk/styles/index.html你可以看到我想要的,但我看了那个代码,我想不通出去。

回答by Simone

The root cause is list-style-type: nonein prettify.css:

根本原因list-style-type: none在 prettify.css 中:

/* Specify class=linenums on a pre to get line numbering */
ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */
li.L0,
li.L1,
li.L2,
li.L3,
li.L5,
li.L6,
li.L7,
li.L8 { list-style-type: none /* <<< THIS is the cause! */ }
/* Alternate shading for lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 { background: #eee }

You can either remove that rule or override it with:

您可以删除该规则或使用以下方法覆盖它:

.linenums li {
    list-style-type: decimal;
}

回答by cwd

Solution

解决方案

Instead of modifying the CSS you can simply add in a line of CSS to achieve the desired behavior:

您可以简单地添加一行 CSS 来实现所需的行为,而不是修改 CSS:

<style>

    .prettyprint ol.linenums > li { list-style-type: decimal; }

</style>  

Example

例子

A full example might have the code below. View results via jsfiddleor see below

一个完整的例子可能有下面的代码。通过 jsfiddle 查看结果或见下文

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css" />

    <style>
        .prettyprint ol.linenums > li { list-style-type: decimal; }
    </style>

<pre class="prettyprint linenums">
 foo
 bar
 bis
 sed
 awk
 cat
</pre>


<script src="//cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/prettify/r298/run_prettify.js"></script>

回答by djunod

I like having the alternating background colors, so did it this way:

我喜欢交替的背景颜色,所以这样做了:

/* White background color for all even-numbered lines */
li.L0,
li.L2,
li.L4,
li.L6,
li.L8  { background-color: #fff; }
/* Light-gray background color for all odd-numbered lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 { background-color: #eee; }