28

現在、プリコード ブロック内に次の 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を使用するか、より簡単な方法があります。

4

5 に答える 5

47

この質問は、先頭の空白を削除するための JavaScript ソリューションまたはより簡単な方法があるかどうかを尋ねます。もっと簡単な方法があります:

CSS

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

デモ

空白

white-spaceプロパティは、要素内の空白の処理方法を記述するために使用されます。

プレライン

一連の空白は折りたたまれます。

于 2015-07-31T20:20:41.893 に答える
9

私は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>ます。)

于 2014-10-07T07:36:28.473 に答える
8

出力方法を変更したいだけかもしれませんが、JavaScript で行うのはかなり簡単です。

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

http://jsfiddle.net/a4gfZ/

于 2013-06-23T02:32:36.300 に答える
0

を使用する場合はpre、レンダリングしたい内容と正確に一致するようにフォーマットする必要があります。preそれがまさに(整形済みテキスト)の考え方です。ただし、インデントだけの場合はmargin-left、適切な負の値を指定して CSS: を使用できます。

于 2013-06-23T06:09:27.010 に答える