DIV CSS 佈局教程網

SyntaxHighlighter 3.0.83 設定與使用筆記
編輯:關於JavaScript     

一、下載

官方網站:https://alexgorbatchev.com/SyntaxHighlighter,本文以 3.0.83 版為例。

二、常用設定

變更要解析的標籤

預設解析 pre,可改為其他標籤:

SyntaxHighlighter.config.tagName = "div";

忽略 HTML 換行標記

若編輯器會在每行尾端插入 <br />,開啟這個選項可讓它略過這些標記。shCore.js 中的實作是:

if (sh.config.stripBrs == true)
  str = str.replace(br, '');

對應的設定寫法:

SyntaxHighlighter.config.stripBrs = true;

隱藏工具列

SyntaxHighlighter.defaults['toolbar'] = false;

三、在頁面中使用

標籤的 class 屬性中,brush 是必填,其餘為選填:

<div class="brush:java;class-name:mycode;highlight:[1,3];">some java code</div>

brush 可取 java、xml、sql、c、js、css 等值,完整清單見官方 manual/brushes/ 頁面。highlight 則用於預先標亮指定行號。

啟動著色有兩種呼叫方式:

SyntaxHighlighter.highlight();
// 或
SyntaxHighlighter.all();

差別在於 all() 會註冊到 onload 事件,適合直接放進頁面;highlight() 則立即執行,適合 yourself 控制時機。

四、在部落格後台調整樣式

部分平台(如舊版痞客邦/論壇)預設已載入 SyntaxHighlighter,此時可用 jQuery 覆寫其內聯樣式。由於 jQuery 無法直接設定帶 !important 的樣式,需改用 cssText:

var sh      = $(".syntaxhighlighter");
var code    = sh.find("code");
var line    = sh.find(".line");
var caption = sh.find("table caption");

sh.css("cssText", "width: auto !important");
code.add(line)
    .add(caption)
    .css("cssText", "font-size: 20px !important;white-space: nowrap !important;line-height: 1.5em !important;");

這段作法的重點在於:SyntaxHighlighter 產出的樣式多帶有 !important,一般的 .css() 設定會被蓋掉,必須整段覆寫 cssText 才有效。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved