javascript - 从 pre/code 标签中缩进的 HTML 源代码中删除前导空格

标签 javascript jquery html css regex

我目前在预代码块中有以下 html:

                <pre class="prettyprint"><code>
                    &lt;html&gt;
                    &lt;body&gt;

                    &lt;form name=&quot;input&quot; action=&quot;html_form_action.asp&quot; method=&quot;get&quot;&gt;
                    &lt;input type=&quot;radio&quot; name=&quot;sex&quot; value=&quot;male&quot;&gt;Male&lt;br&gt;
                    &lt;input type=&quot;radio&quot; name=&quot;sex&quot; value=&quot;female&quot;&gt;Female&lt;br&gt;
                    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
                    &lt;/form&gt; 

                    &lt;p&gt;If you click the &quot;Submit&quot; button, the form-data will be sent to a page called &quot;html_form_action.asp&quot;.&lt;/p&gt;

                    &lt;/body&gt;
                    &lt;/html&gt;
                </code></pre>

它在 html 源代码中缩进,以便在文档中获得更好的结构。如何删除前导空格?通过使用javascript还是有更简单的方法。

最佳答案

问题询问是否有 JavaScript 解决方案或更简单的方法来删除前导空格。有一个更简单的方法:

CSS

pre, code {
    white-space: pre-line;
}

DEMO

white-space

The white-space property is used to describe how whitespace inside the element is handled.

pre-line

Sequences of whitespace are collapsed.

为了保留现有的空白或缩进,每一行都可以包含在子标记中,并在行级别将 white-space 重置为 pre:

HTML

<pre>
    <code>
        <i>fn main() {</i>
        <i>    println!("hello world!");</i>
        <i>}</i>
    </code>
</pre>

CSS

pre, code {
    white-space: pre-line;
}

pre > code > i {
    white-space: pre;
}

关于javascript - 从 pre/code 标签中缩进的 HTML 源代码中删除前导空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17257200/

相关文章:

javascript - GWT 中的深度克隆

javascript - 单击一定数量后更改 div 背景

html - 如何将现代 HTML 转换为 PDF

javascript - 如何获取 Jquery Datatable 中字符串格式的选定值

javascript - 为什么 Javascript 函数在 Chrome 77.0.3865.120 和 Safari 13.0.2 上的行为不同?

javascript - 显示范围或htmlfrag的html内容

javascript - 我可以使用 jQuery 在 GWT 小部件上触发事件吗?

jquery - Bootstrap 面板标题 - 右对齐控件

javascript - 从 html 页面中删除/禁用样式表

html - 如何剥离内联格式页面并将其设置为外部格式?