簡體   English   中英

如何在不犧牲空格的情況下縮進代碼

[英]How Can I Indent Code Without Sacrificing Whitespace

我有以下HTML5代碼。

        <code>
            public class Testing {
                public static void main(String[] args) {
                    System.out.println("Hello World");
                }
            }
        </code>

但在頁面上,它只放在一行上,沒有使用適當的縮進。

我知道我可以使用<pre>標簽使它按我想要的方式工作,但是使用該標簽的問題是它會使代碼向右縮進太遠,如果我將代碼向左移,它將弄亂了HTML代碼的空格和縮進。 無論如何,我可以使代碼以我想要的方式顯示在頁面上,而不必犧牲空格和干凈的HTML代碼嗎? 謝謝。

編輯:這與潛在的重復項不同,因為它使用了pre標記,並且沒有解決犧牲空格的問題。

添加一個css規則,該規則根據您的喜好格式化pre標簽。

 .code { margin: 0 0 0 -0.5em; } 
 <pre> standard <pre> <pre class="code"> styled <pre> 

Adrian的答案是完全有效的,但如果您的“絕對”文本縮進在HTML文件中的每個代碼塊之間不完全相同,則該答案將無效。 不幸的是,我看不出CSS可以做得更好。

您還可以使用腳本來掃描代碼塊(在示例中按類,但可以使用getElementsByTagName 。它在頁面加載時運行,並查看每個節點的第一行,並假定必須有相同數量的空格。在每行刪除。

不利的一面是,當使用大量積木時,由於刪除了空格,這種方式會產生一些奇怪的視覺效果。

 function parseCode() { if (document.readyState === "interactive" || document.readyState === "complete" ) { const nodes = document.getElementsByClassName('code'); for(let node of nodes) { const lines = node.innerText.split("\\n"); const first = lines[0].length ? lines[0] : lines[1]; const output = []; let read = ' '; let spacesToRemove = 0; while(read === ' ') { read = first[spacesToRemove]; if(read === ' ') spacesToRemove++; } lines.forEach(line => output.push(line.substr(spacesToRemove))); node.innerText = output.join("\\n"); } } } document.addEventListener("DOMContentLoaded", parseCode); 
 .code { white-space: pre } 
 <pre> public class Testing { public static void main(String[] args) { System.out.println("Hello World"); } } </pre> <code class="code"> public class Testing { public static void main(String[] args) { System.out.println("Hello World"); } } </code> 

暫無
暫無

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

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