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