如何忽略html中的前导和尾随换行符;代码“;是否使用css、javascript或jquery阻止?

如何忽略html中的前导和尾随换行符;代码“;是否使用css、javascript或jquery阻止?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,在我的HTML源代码中,我有如下代码块(我在此页面上使用shodown和highlight.js): double myNumber=(double)4; 我的问题是第一个换行符仍然是“代码”块的一部分。这可能是因为包含了“pre”块,但我需要它,因为highlight.js需要它(显然也是HTML5标准)。代码的呈现方式如下(请注意前导行分隔符): 所以我的问题是,使用css、javascript或jquery,如何从像这样的“代码”块中删除前导或尾随换行符?演示: 在PC上使用Chr

在我的HTML源代码中,我有如下代码块(我在此页面上使用shodown和highlight.js):


double myNumber=(double)4;
我的问题是第一个换行符仍然是“代码”块的一部分。这可能是因为包含了“pre”块,但我需要它,因为highlight.js需要它(显然也是HTML5标准)。代码的呈现方式如下(请注意前导行分隔符):

所以我的问题是,使用css、javascript或jquery,如何从像这样的“代码”块中删除前导或尾随换行符?演示:

在PC上使用Chrome和FF进行测试。当插件应用于
code
元素时,它在IE 9中不起作用(当应用于
pre
元素时,它似乎工作正常)。我找不到合适的解决方法,但请随意评论/更新

这是来自的修改版本。这个插件试图删除文档自然流动所造成的额外缩进。我已经对它进行了修改,使其在引导空白方面更为明智

如果它工作正常,您应该看到如下内容:

用法
$(“code”).prettyPre();//此处的任何选择器

带前导空格和额外缩进的HTML


double myNumber=(double)4;
//另一行
//另一行
//这是故意进一步缩进的
对于(变量i=0;i<100;i++){
}            
插件
(函数($){
$.fn.prettyPre=函数(方法){
var默认值={
ignoreExpression://\s///应该忽略什么?
};
var方法={
初始化:函数(选项){
这个。每个(函数(){
var context=$.extend({},默认值,选项);
var$obj=$(本);
var usinginertext=真;
var text=$obj.get(0).innerText;
//有些浏览器支持innerText…有些不支持…有些只支持innerText。
如果(文本类型==“未定义”){
text=$obj.html();
usinginertext=false;
}
//使用第一行作为存在多少不需要的前导空白字符的基线
var多余空间计数=0;
var-pos=0;
var currentChar=text.substring(0,1);
while(context.ignoreExpression.test(currentChar)){
如果(currentChar!==“\n”){
多余的spacecount++;
}否则{
多余空间计数=0;
}
currentChar=text.substring(++pos,pos+1);
}
//分裂
var parts=text.split(“\n”);
var reformattedText=“”;
//重建
变量长度=零件长度;
对于(变量i=0;i
默认情况下,
pre
就是这样工作的:它尊重换行符和空格。如果不想渲染换行符,则必须将其删除。如果您关心源代码的外观,可以直接将其从源代码中删除,也可以将其注释掉

double myNumber=(double)4

您可以使用此黑客:


下面是另一种使用Javascript的方法,它也解决了这个问题:


window.onload=函数(){
//从代码块中删除前导换行符。
var pre=document.getElementsByTagName(“代码”);
对于(变量i=0,len=pre.length;i

其他人发布了这个,然后删除了他们的答案,但我认为它值得保留。

这些函数使用一个类(添加到
pre
中)来删除前导和尾随空格

.indent-14{
背景色:#ccc;
}

点击我

函数createCORSRequest(方法,url){
var request=new XMLHttpRequest();
<pre><code class="cpp">
double myNumber = (double)4;
</code></pre>
<div>
        <pre><code class="cpp">
           double myNumber = (double)4;

           // another line

           // another line

                // this is purposely indented further
                for( var i = 0; i < 100; i++ ){

                }            

        </code></pre>
</div>
(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 pos = 0;
                    var currentChar = text.substring( 0, 1 );

                    while ( context.ignoreExpression.test( currentChar ) ) {
                        if(currentChar !== "\n"){
                            superfluousSpaceCount++;
                        }else{
                            superfluousSpaceCount = 0;
                        }

                        currentChar = text.substring( ++pos, pos + 1 );
                    }

                    // split
                    var parts = text.split( "\n" );
                    var reformattedText = "";

                    // reconstruct
                    var length = parts.length;
                    for ( var i = 0; i < length; i++ ) {

                        // remove leading whitespace (represented by an empty string)
                        if(i === 0 && parts[0]=== ""){
                            continue;   
                        }

                        // 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 );
<pre><code class="cpp"><!--
-->double myNumber = (double)4;<!--
--></code></pre>
pre:first-line {
    line-height: 0;
}
<script>
    window.onload = function (){
        // remove leading linebreaks from code blocks.
        var pre = document.getElementsByTagName("code");
        for (var i = 0, len = pre.length; i < len; i++) {
            var text = pre[i].firstChild.nodeValue;
            pre[i].firstChild.nodeValue = text.replace(/^\n+|\n+$/g, "");
        }
    }
</script>
function removeWhitespace(indent) {
  // Get a list of all elements that need whitespace removed by indent value (will have class `indent-X`)
  // List may be 0 long - loop simply doesn't run
  var preElements = document.getElementsByClassName('indent-'+indent);
  for (i = 0; i < preElements.length; i++) {
    preElements[i].innerHTML = preElements[i].innerHTML.split('\n'+' '.repeat(indent)).join('\n').split('\n'+' '.repeat(indent-2)+'</code>').join('</code>').split("\n").slice(1,-1).join("\n");
    //split('\n'+' '.repeat(indent)).join('\n') -- Split at every newline followed by X spaces. Then join together with the newlines.
    // .split('\n'+' '.repeat(indent-2)+'</code>').join('</code>') -- The lastline will have 2 less spaces, so remove those, and the newline at the end. Add the tag back in.
    //.split("\n").slice(1,-2).join("\n"); -- Remove the first and last lines.
  }
}

function removeWhitespaces() {
  // Loop over all indents, 2 to 40
  for (indent = 2; indent <= 40; indent+=2) {
    removeWhitespace(indent);
  }
}