簡單究好 Simple is Best

網頁前端開發資訊

Google Code Prettify – 程式碼上色工具

Google Code Prettify 是一套幫程式語法上色的工具、用法非常簡單、只要引用他的CSS和javascript之後、再把要上色的程式碼用<pre  class=”prettyprint”>的標籤包起來,最後別忘了在body的標籤內加上 onload=”prettyPrint()”就可以了

Step1
下載並解壓縮Google Code Prettify
下載位置

Step2
引用 CSS 和 JavaScript:

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

或是利用底下路徑同時載入CSS及JavaScript

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js">

Step3
標記程式碼
prettify.js支援<pre>, <code>, 和<xmp>三種標籤。只要用其中一種將程式碼包起來、並設定class=”prettyprint”就可了
程式碼當中若有 < 符號,記得轉換成特殊字元 &lt;

<pre class="prettyprint">
你的 code 放這邊!
</pre>

利用<pre>或<code>及class將有需要上色的字串、註譯包起來

<pre class=prettyprint>
int x = foo();  /* This is a comment  This is not code
  Continuation of comment */
int y = bar();
</pre>

<pre>, <code>, 和<xmp>同時具有等寬字型的特性。
<code>用來表示原始碼,
<pre>和<xmp>則是定義預格式化的文本。不過在html5的語言中,<xmp>已經完全遭到刪除、因此不建議使用。而<pre>則是可以保留空格和換行符號因此在使用上比較方便。

Step4
呼叫函數
prettyPrint(); 可以放在body 裡面

<body onload="prettyPrint();">

也可以放在要引用的程式碼之後

<script>
prettyPrint();
</script>

Step5
換個樣式
prettify.js 還有其他不同的樣式,可以在 skin gallery 找到。
當然您也可以自訂一個自己喜歡的樣式。

行號提示
pre 的 class 加上linenums,就可以有行號提示的效果。google code prettify的行號提示以5行為一個單位。

<pre class="prettyprint linenums">
多行程式碼
A();
B();
C();
D();
E();
F();
G();
H();
</pre>

在linenums後加上:數字還可以指定開始的行號、如果原始碼比較長、需要分段時,指定開始的行號是一個不錯的方法。

<pre class="prettyprint linenums:4">
這是第4行,linenums:4
A();
B();
C();
</pre>

上面原始碼呈現的效果如下:

這是第4行,linenums:4
A();
B();
C();

若是希望每行都有提示,那就加上底下的 CSS 設定

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

支援瀏覽器:IE 6, Firefox 1.5 & 2, Safari 2.0.4.
如果想要看看您的瀏覽器是否支援Google Code Prettify,可以試試測試頁面

套件名稱:google code prettify
套件網址:https://code.google.com/p/google-code-prettify/
樣式主題:http://google-code-prettify.googlecode.com/svn/trunk/styles/index.html
下載網址:https://code.google.com/p/google-code-prettify/downloads/list
測試頁面:https://google-code-prettify.googlecode.com/svn/trunk/tests/prettify_test.html

One Comment

Post a comment

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *