PRE
表示されているとおりに空白を保持することを目的としています (white-space
書式設定コードをサポートするのに十分な柔軟性がない CSS で変更されない限り)。
前
フォーマットは保持されますが、PRE
タグの外側のすべてのインデントも保持されます。タグの場所を出発点として使用する空白の保存があるとよいでしょう。

後
コンテンツは宣言どおりにフォーマットされPRE
ますが、ドキュメント内のタグの位置によって生じる余分な先頭の空白は削除されます。

ドキュメント アウトラインのインデントによって発生する余分な空白を削除したいという問題を解決するために、次のプラグインを思い付きました。このコードは、PRE タグ内の最初の行を使用して、純粋にドキュメントのインデントが原因でどの程度インデントされたかを判断します。
このコードは、IE7、IE8、IE9、Firefox、および Chrome で機能します。Prettifyライブラリを使用して簡単にテストし、保存された書式設定ときれいな印刷を組み合わせました。内の最初の行が、PRE
無視するインデントのベースライン レベルを実際に表していることを確認してください (または、プラグインをよりインテリジェントに変更できます)。
これは大まかなコードです。間違いを見つけたり、思い通りに動作しない場合は、修正/コメントしてください。ただ反対票を投じないでください。私が抱えていた問題を修正するためにこのコードを書きましたが、積極的に使用しているので、できるだけしっかりしたものにしたいと思います!
/*!
*** prettyPre ***/
(function( $ ) {
$.fn.prettyPre = function( method ) {
var defaults = {
ignoreExpression: /\s/ // what should be ignored?
};
var methods = {
init: function( options ) {
this.each( function() {
var context = $.extend( {}, defaults, options );
var $obj = $( this );
var usingInnerText = true;
var text = $obj.get( 0 ).innerText;
// some browsers support innerText...some don't...some ONLY work with innerText.
if ( typeof text == "undefined" ) {
text = $obj.html();
usingInnerText = false;
}
// use the first line as a baseline for how many unwanted leading whitespace characters are present
var superfluousSpaceCount = 0;
var currentChar = text.substring( 0, 1 );
while ( context.ignoreExpression.test( currentChar ) ) {
currentChar = text.substring( ++superfluousSpaceCount, superfluousSpaceCount + 1 );
}
// split
var parts = text.split( "\n" );
var reformattedText = "";
// reconstruct
var length = parts.length;
for ( var i = 0; i < length; i++ ) {
// cleanup, and don't append a trailing newline if we are on the last line
reformattedText += parts[i].substring( superfluousSpaceCount ) + ( i == length - 1 ? "" : "\n" );
}
// modify original
if ( usingInnerText ) {
$obj.get( 0 ).innerText = reformattedText;
}
else {
// This does not appear to execute code in any browser but the onus is on the developer to not
// put raw input from a user anywhere on a page, even if it doesn't execute!
$obj.html( reformattedText );
}
} );
}
}
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ) );
}
else if ( typeof method === "object" || !method ) {
return methods.init.apply( this, arguments );
}
else {
$.error( "Method " + method + " does not exist on jQuery.prettyPre." );
}
}
} )( jQuery );
このプラグインは、標準の jQuery セレクターを使用して適用できます。
<script>
$( function() { $("PRE").prettyPre(); } );
</script>