2018年6月15日 星期五

[blogger] Google Code Prettify測試-在blogger中嵌入上色的code

在blogger裡面放code的簡單方法,用google code-prettify

效果:


  1. int x = foo(); /* This is a comment This is not code Continuation of comment */
  2.  
  3. int y = bar();


讓code的關鍵字可以自動上色,更方便觀看

使用方式:


1.加入 Google Code Prettify小工具



Layout > Add a Gadget > HTML/JavaScriptAdd

context 的部分輸入下列程式碼

  1. <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=desert""></script>

其中?skin=desert用來指定程式碼的skin,可以選擇的skin可以參考這邊

 2.在文章中加入區段標記


將文章中的程式法區段以

<pre class="prettyprint">...</pre>包起來
例如:
  1. <pre class="prettyprint linenums">int x = foo();  /* This is a comment  This is not code  Continuation of comment */
  2.  
  3. <span class="pre-highborder">
  4.  
  5. int y = bar();</span>
  6.  
  7. </pre>
需要特別注意的是,最好不要直接把程式碼貼進HTML中,而最好是先在 "Compose" 頁面中將code貼上,在切換到"HTML"頁面去加上<pre>...</pre>的tag, 不然程式碼中如果包含特殊字元(通常都有包含)顯示就會跟內容來源不一樣

另外雖然prettyprint會自動偵測語言,但在乎叫的時候也可以用

<pre class="prettyprint lang-html">

來指定語言
html可以換成

    "bsh", "c", "cc", "cpp", "cs", "csh", "cyc", "cv", "htm", "html", "java",
    "js", "m", "mxml", "perl", "pl", "pm", "py", "rb", "sh", "xhtml", "xml",
    "xsl".


2.1 顯示行數

加入linenums:n, n是起始和數,幾行顯示一次跟選擇的顯示style有關
<pre class="prettyprint linenums">..</pre>

bouns1. 程式碼中highlight 部分程式段


首先在Theme>Edit HTML中的 </head 之前> 加上
  1. <style type='text/css'>
  2.  
  3. .pre-highborder{
  4.  
  5. border: 1px solid #ff0000;
  6.  
  7. padding: 3px 3px 3px 0;
  8.  
  9. }
</style>

接著在code中將想要highlight的地方以

<span class="pre-highborder">...</span>

包圍

參考資料


bouns2. 加入scroll bar

  1. <style type='text/css'>
  2.  
  3. pre.prettyprint{
  4. width: auto;
  5. overflow: auto;
  6. max-height: 600px
  7. }
  8.  
  9. </style>
參考資料

bonus3. 變換背景顏色跟行號顏色


  1. <style type='text/css'>
  2.  
  3. /*each line*/
  4.  
  5. li.L0, li.L1, li.L2, li.L3, li.L4, li.L5, li.L6, li.L7, li.L8, li.L9 {
  6.  
  7.  margin: 0 !important;
  8.  
  9.  list-style-type:decimal !important;
  10.  
  11.  border-left: 1px solid #999;
  12.  
  13. background-color: #4f4f4f  !important;
  14.  
  15. }
  16.  
  17.  
  18.  
  19. ol.linenums {
  20.  
  21.  background-color: #3f3f3f  !important;;
  22.  
  23.  margin-left: 10px;
  24.  
  25. }
  26.  
  27. </style>

在試這段code的時候發現code裡面有 "!important"這種東西出現,一開始以為是註解,不以為意,還把他刪掉。但發現刪掉會影響程式行為。
大致上來說,被!important所標註的參數會有比較高的 priority, 前面的設定可以覆蓋後面的。正常情況是後面的參數會蓋前面的參數。
詳細說明可以猜考這裡

沒有留言:

張貼留言