3

所以,我通常像这样格式化我的 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 解决方案。有吗?

4

1 回答 1

3

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

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

于 2012-01-16T18:53:47.210 回答