解決代碼着色組件SyntaxHighlighter行號顯示問題


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();之前執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM