因此,我通常将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解决方案。有吗?
没有CSS解决方案,除非您可以在pre
元素上设置负边距,但您需要使用一个固定的数字和ch
单元来设置它(这不是普遍支持的)。这将是相当笨拙、不灵活和不可靠的。
pre
元素意味着预先格式化的文本,除非您真的想要,否则不应该使用它。对于程序代码,您可以只使用强制换行符(<br>
)和用于缩进的前导无中断空格(理论上不可靠,但在实践中有效)。然而,只包含要显示为预格式化的数据是最简单、最安全的,即使它破坏了HTML源的布局(只有少数阅读过它的人感兴趣)。