したがって、私は通常、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 ソリューションを好むでしょう。ありますか?