簡體   English   中英

從pre / code標簽中的縮進HTML源中刪除前導空格

[英]Removing leading whitespace from indented HTML source in pre/code tags

我目前在預代碼塊中有以下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屬性用於描述如何處理元素內的空白。

前行

空白的序列被折疊。

我真的很喜歡Homam的想法,但我不得不改變它來處理這個問題:

<pre><code><!-- There's nothing on this line, so the script thinks the indentation is zero -->
    foo = bar
</code></pre>

要解決這個問題,如果它是空的,我只需取出第一行:

[].forEach.call(document.querySelectorAll('code'), function($code) {
    var lines = $code.textContent.split('\n');

    if (lines[0] === '')
    {
        lines.shift()
    }

    var matches;
    var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null;
    if (!!indentation) {
        lines = lines.map(function(line) {
            line = line.replace(indentation, '')
            return line.replace(/\t/g, '    ')
        });

        $code.textContent = lines.join('\n').trim();
    }
});

(我也在處理<code>標簽而不是<pre>標簽。)

您可能只想更改輸出方式,但使用JavaScript非常簡單

var p = document.querySelector(".prettyprint");
p.textContent = p.textContent.replace(/^\s+/mg, "");

http://jsfiddle.net/a4gfZ/

擴展上面的解決方案,這段代碼假設<pre>內第一行的縮進為0,它根據第一行重新排列所有行:

[].forEach.call(document.querySelectorAll('pre'), function($pre) {
  var lines = $pre.textContent.split('\n');
  var matches;
  var indentation = (matches = /^\s+/.exec(lines[0])) != null ? matches[0] : null;
  if (!!indentation) {
    lines = lines.map(function(line) {
      return line.replace(indentation, '');
    });
    return $pre.textContent = lines.join('\n').trim();
  }
});

當您使用pre ,您應該將其內容格式化為您想要呈現的內容。 這就是pre (預先格式化的文本)的想法。 但如果它只是縮進,你可以使用CSS: margin-left和一個合適的負值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM