Automatic line break in js SyntaxHighlighter

时光毁灭记忆、已成空白 提交于 2019-11-30 08:29:19

I don't actually use SyntaxHighlight, but it seems to be possible to attach an white-space: pre-wrap CSS style to the <pre> or <script> tag that SyntaxHighlight uses.

HTML (using <pre>):

<pre class="brush: js" class="syntaxhighlight">
    /**
     * SyntaxHighlighter
     */
    function foo()
    {
        if (counter <= 10)
            return;
        // it works!
    }
</pre>

HTML (using <script>):

<script type="syntaxhighlighter" class="syntaxhighlight brush: js"><![CDATA[
    /**
     * SyntaxHighlighter
     */
    function foo()
    {
        if (counter <= 10)
            return;
        // it works!
    }
]]></script>

CSS:

.syntaxhighlight {
    white-space: pre-wrap;
}

The wrap is no longer an option but you can add the functionality easily.

Add this to the css to break the lines

body .syntaxhighlighter .line {
        white-space: pre-wrap !important; /* make code wrap */
}

To fix the line numbering use the script below.

function lineWrap(){
    var wrap = function () {
        var elems = document.getElementsByClassName('syntaxhighlighter');
        for (var j = 0; j < elems.length; ++j) {
            var sh = elems[j];
            var gLines = sh.getElementsByClassName('gutter')[0].getElementsByClassName('line');
            var cLines = sh.getElementsByClassName('code')[0].getElementsByClassName('line');
            var stand = 15;
            for (var i = 0; i < gLines.length; ++i) {
                var h = $(cLines[i]).height();
                if (h != stand) {
                    console.log(i);
                    gLines[i].setAttribute('style', 'height: ' + h + 'px !important;');
                }
            }
        }
     };
    var whenReady = function () {
        if ($('.syntaxhighlighter').length === 0) {
            setTimeout(whenReady, 800);
        } else {
            wrap();
        }
    };
    whenReady();
};
lineWrap();
$(window).resize(function(){lineWrap()});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!