web-dev-qa-db-ja.com

HTMLのインデントを削除せずに、<pre> / <code>ブロックの先頭の空白を削除するにはどうすればよいですか?

次のHTMLがあります。

<body>
    Here is some code:

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

しかし、プレビューすると、コードがインデントされているので、preはまったく問題ありません。内容をインデントに戻すことで修正できますが、見た目はばかげています。上記のテキストをインデントしないようにできますか?

18
Doug Smith

あなたはこれを多分試すことができます:

pre, code{
    white-space:normal;
}

フィドル

10
zgood

では、precodeの作業方法を変更するよりも具体的な方法を考えました。したがって、最初の改行文字_\n_を取得するためにいくつかの正規表現を作成しました(可能な空白文字を前に付けます-_\s*_は、コードの行の終わりと改行文字の前の余分な空白文字をクリーンアップするために使用されます(これはあなたが持っていたことに気付きました))、それに続くタブまたは空白文字を見つけます_[\t\s]*_(つまり、タブ文字、空白文字(0以上)を意味し、その値を変数に設定します。その変数は正規表現の置換関数で使用されますそのすべてのインスタンスを検索して_\n_(改行)で置き換えます。2行目(patternが設定される場所)にはグローバルフラグ(a 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>_
4
ctwheels

これは機能しますが、インデントはコードの最初の行に基づく必要があると想定しています。

//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>
1
Rick Hitchcock