如何删除 <pre>/<code> 块中的前导空格而不删除 HTML 中的缩进? [重复]

问题描述 投票:0回答:3

我有以下 HTML:

<body>
    Here is some code:

    <pre><code>
        Here is some fun code!    
    </code></pre>
</body>

但是当我预览它时,由于代码是缩进的,所以 pre 完全不正常。我可以通过将内容带回缩进来解决这个问题,但这看起来很愚蠢。我可以让上面的文字看起来不缩进吗?

html css pre
3个回答
32
投票

你也许可以尝试一下:

pre, code {
    white-space: normal;
}

小提琴


13
投票

给你,我决定想出一些比改变

pre
code
工作方式更具体的东西。所以我做了一些正则表达式来获取第一个换行符
\n
(前面可能有空格 -
\s*
用于清除代码行末尾和换行符之前的额外空格(我注意到你的换行符有) )并找到其后面的制表符或空格字符
[\t\s]*
(这意味着制表符、空格字符(0 个或多个)并将该值设置为变量。然后在正则表达式替换函数中使用该变量来查找它的所有实例并将其替换为
\n
(换行符)。由于第二行(设置
pattern
的位置)没有全局标志(正则表达式后面的
g
),因此它将找到
\n 的第一个实例。 
换行符并将
pattern
变量设置为该值,因此,在换行符后跟 2 个制表符的情况下,
pattern
的值在技术上将是
\n\t\t
,它将在每个
\n
时被替换。字符在该
pre code
元素中找到(因为它贯穿每个函数)并替换为
\n

$("pre code").each(function(){
    var html = $(this).html();
    var pattern = html.match(/\s*\n[\t\s]*/);
    $(this).html(html.replace(new RegExp(pattern, "g"),'\n'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
    Here is some code:

    <pre><code>
        Here is some fun code!
        More code
          One tab
            One more tab
            
            Two tabs and an extra newline character precede me
    </code></pre>
</body>


2
投票

这是可行的,假设缩进应该基于第一行代码:

//get the code element:
var code= document.querySelector('pre code');

//insert a span in front of the first letter.  (the span will automatically close.)
code.innerHTML= code.textContent.replace(/(\w)/, '<span>$1');       

//get the new span's left offset:
var left= code.querySelector('span').getClientRects()[0].left;      

//move the code to the left, taking into account the body's margin:
code.style.marginLeft= (-left + code.getClientRects()[0].left)+'px';  
code {
  display: block;  //this is necessary for the JavaScript to work properly
}
<body>
    Here is some code:

    <pre><code>
        Here is some fun code!    
          And some more!
            Continuing
          Wrapping up
        Closing code now.
    </code></pre>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.