解决PRE元素中多余的空白问题

时间:2012-01-16 18:42:55

标签: javascript jquery html css pre

因此,我通常会格式化我的HTML源代码:

<article>
    <section>
        <p>
            Text...
            Text...
        </p>
        <pre>
            Code...
            Code...
            Code...
        </pre>
        <p>
            Text...
            Text...
        </p>
    </section>
</article>

但是,这种格式化样式与PRE元素不兼容,因为这些元素中的所有空格都很重要。

请参见此处: http://jsfiddle.net/pjEYm/

为了修复代码块的表示,我必须像这样格式化源代码:

<article>
    <section>
        <p>
            Text...
            Text...
        </p>
        <pre>
            Code...
Code...
Code...</pre>
        <p>
            Text...
            Text...
        </p>
    </section>
</article>

请参见此处: http://jsfiddle.net/pjEYm/1/

然而,这会降低我的源代码的整洁性和可读性。

我想使用一种能让我保留格式化风格的解决方案。

我尝试设置white-space属性。最接近解决方案的是white-space: pre-line,但它也会删除代码中的所有缩进。

请参见此处: http://jsfiddle.net/pjEYm/2/show/

所以,我选择了JavaScript:

$( 'pre' ).each( function () {
    var lines, offset;

    // split the content of the PRE element into an array of lines
    lines = $( this ).text().split( '\n' );

    // the last line is expected to be an empty line - remove it
    if ( lines.length > 1 && lines[ lines.length - 1 ].trim() === '' ) {
        lines.pop();
    }

    // how much white-space do we need to remove form each line?
    offset = lines[ 0 ].match( /^\s*/ )[ 0 ].length;

    // remove the exess white-space from the beginning of each line
    lines = lines.map( function ( line ) {
        return line.slice( offset );
    });

    // set this new content to the PRE element
    $( this ).text( lines.join( '\n' ) );
});

现场演示: http://jsfiddle.net/pjEYm/3/

虽然这有效,但我仍然更喜欢某种 CSS解决方案。有吗?

1 个答案:

答案 0 :(得分:3)

没有CSS解决方案,除非您可以在pre元素上设置负边距,但是您需要使用固定数字和ch单位设置它(这是普遍支持的)。这将是相当笨拙,不灵活和不可靠的。

pre元素表示预先格式化的文本,除非您真的需要,否则不应使用它。对于程序代码,您可以使用强制换行符(<br>)和前导不间断空格进行缩进(理论上,不可靠,但在实践中有效)。然而,将您想要显示的数据包含在预先格式化中是最简单和最安全的,即使它打破了HTML 的布局(仅对少数读取它的人感兴趣)。

相关问题