PRE 旨在保留空白,与它看起来完全一样(除非在 CSS 中被 white-space 更改,它没有足够的灵活性来支持格式化代码)。
之前
格式被保留,但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>