SyntaxHighlighter 代码换行行号对不上、行号显示错误及代码太长无法换行解决办法

SyntaxHighlighter是一个使用JavaScript编写的功能齐全的代码语法高亮的软件。如果一行代码或注释太长的话在页面中显示时需要分成多行显示,这时行号就对不上了,如下图:

image.png

SyntaxHighlighter自动换行以及更正行号的方法解决方法:

引入下面的css,强制长代码换行,放在SyntaxHighlighter的代码后面替换里面的样式。代码如下:

.syntaxhighlighter{width:100%!important;}
.syntaxhighlighter .line {
white-space: pre-wrap !important;
word-break: break-all;
}
.syntaxhighlighter .gutter .line{width:22px !important;}
.syntaxhighlighter td.code .container::before, .syntaxhighlighter td.code .container::after {display: none;}
/* 如果是需要保留一行内的单词完整性则需要把 break-all 改为 break-word  */

这个时候,如果行号的高度和代码的高度不能保持一致了。引入下面的代码:

$(function() { // Line wrap back
  var shLineWrap = function() {
    $('.syntaxhighlighter').each(function() { // Fetch
      var $sh = $(this),
        $gutter = $sh.find('td.gutter'),
        $code = $sh.find('td.code'); // Cycle through lines
      $gutter.children('.line').each(function(i) { // Fetch
        var $gutterLine = $(this),
          $codeLine = $code.find('.line:nth-child(' + (i + 1) + ')'); //alert($gutterLine);
        // Fetch height
        var height = $codeLine.height() || 0;
        if(!height) {
          height = 'auto';
        } else {
          height = height += 'px'; //alert(height);
        } // Copy height over
        $gutterLine.attr('style', 'height: ' + height + ' !important'); // fix by Edi, for JQuery 1.7+ under Firefox 15.0
        console.debug($gutterLine.height(), height, $gutterLine.text(), $codeLine);
      });
    });
  };

  // Line wrap back when syntax highlighter has done it's stuff
  var shLineWrapWhenReady = function() {
    if($('.syntaxhighlighter').length === 0) {
      setTimeout(shLineWrapWhenReady, 10);
    } else {
      shLineWrap();
    }
  }; // Fire
  shLineWrapWhenReady();
});

插入到页面底部(SyntaxHighlighter.all()方法后面也行),本方法是基于JQuery写的,大家用这种方法之前请务必引入JQuery文件!

修改完成后效果如下图:

image.png

© 版权声明
THE END