因此,通常我会像这样格式化HTML源代码:
Text...
Text...
Code...
Code...
Code...
Text...
Text...
但是,此格式样式与PRE元素不兼容,因为这些元素内的所有空白都很重要.
为了修复代码块的表示形式,我将必须像这样格式化源代码:
Text...
Text...
Code...
Code...
Code...
Text...
Text...
但是,这降低了我的源代码的整洁度和可读性.
我想使用一种解决方案,使我能够保留自己的格式设置样式.
我尝试设置空白属性.最接近解决方案的是空格:换行符,但它也会删除代码中的所有缩进.
因此,我使用了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' ) );
});
虽然这可行,但我仍然希望使用某种CSS解决方案.有一个吗?
解决方法:
没有CSS解决方案,除了可以在pre元素上设置负边距之外,但是您将需要使用固定数字和ch单位(不受普遍支持)来设置它.这将是相当笨拙,不灵活且不可靠的.
pre元素表示预格式化的文本,除非真正需要,否则不要使用它.对于程序代码,您可以仅使用强制换行符(< br>)和前导不间断空格进行缩进(从理论上讲,不是可靠的,但实际上是可行的).但是,只包含要显示为预格式化的数据是最简单和最安全的方法,即使它破坏了HTML源代码的布局(只有少数阅读它的人也会感兴趣).
标签:pre,css,html,javascript,jquery
来源: https://codeday.me/bug/20191201/2083991.html