解决代码着色组件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();之前执行。

posted @ 2014-11-25 18:27  dudu  阅读(2789)  评论(8编辑  收藏  举报