文章出處

SyntaxHighlighter是根據代碼中的換行符分配行號的。但是,如果一行代碼或者注釋比較長,在頁面顯示時需要分成多行顯示,這時行號就對不上了。如下圖:

 

通過下面的css強制不換行,可以避開這個問題。

.syntaxhighlighter .line {
    white-space: pre !important;
}

但這樣會出現橫向滾動條,而不想出現橫向滾動條,css要改為這樣:

.syntaxhighlighter .line {
    white-space: pre-wrap !important;
}

但這樣行號又對不上。

后來,我們采用了一種折衷的解決方法:

如果代碼著色時使用了行號,就用 white-space: pre !important; (強制不換行)

如果代碼著色時沒有使用行號,就用 white-space: pre-wrap !important; (強制換行)

解決方法看起來很簡單,但實現起來沒那么容易,因為要動態切換css,后來只找一個解決方法,動態加載css文件,示例代碼如下:

var shpre = $('div.cnblogs_Highlighter pre:first');
if (shpre.length) {
    if (shpre.attr('class').indexOf('gutter:true;') > 0) {
        $("head").append("<link>");
        var css = $("head").children(":last");
        css.attr({
            rel: "stylesheet",
            type: "text/css",
            href: "/css/sh_gutter.css"
        });
    }
}

【參考資料】

How To Switch CSS Files On-The-Fly Using jQuery

【更新】

@undefined 在評論中給出了更好的解決方案,驗證有效,分享一下:

1)在css中增加一個可以覆蓋.syntaxhighlighter .line的樣式

.sh-gutter .line{ white-space: nowrap!important; }

2)在js代碼中判斷如果是有行號的代碼,通過addClass添加這個樣式

var shpres = $('div.cnblogs_Highlighter pre');
if (shpres.length) {
    $.each(shpres, function () {
        if ($(this).attr('class').indexOf('gutter:true;') > 0) {
            $(this).parent().addClass('sh-gutter');
        }
    });
}

注:以上js代碼需要放在SyntaxHighlighter.all();之前執行。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()