2012-01-16 82 views
3

所以,我通常格式化我的HTML源代碼如下所示:麻煩過剩空白PRE元素中

<article> 
    <section> 
     <p> 
      Text... 
      Text... 
     </p> 
     <pre> 
      Code... 
      Code... 
      Code... 
     </pre> 
     <p> 
      Text... 
      Text... 
     </p> 
    </section> 
</article> 

然而,這種格式的風格不符合,因爲這些元素中所有空白PRE元素兼容意義重大。

在這裏看到:http://jsfiddle.net/pjEYm/

爲了修復代碼塊的呈現,我將不得不格式化的源代碼如下所示:

<article> 
    <section> 
     <p> 
      Text... 
      Text... 
     </p> 
     <pre> 
      Code... 
Code... 
Code...</pre> 
     <p> 
      Text... 
      Text... 
     </p> 
    </section> 
</article> 

在這裏看到:http://jsfiddle.net/pjEYm/1/

然而,這降低了我的源代碼的整潔性和可讀性。

我想用一個解決辦法,使我保持自己的格式樣式。

我嘗試設置white-space財產。最接近解決方案的是white-space: pre-line,但它也從代碼中刪除所有縮進。

在這裏看到:http://jsfiddle.net/pjEYm/2/show/

所以,我用JavaScript去:

$('pre').each(function() { 
    var lines, offset; 

    // split the content of the PRE element into an array of lines 
    lines = $(this).text().split('\n'); 

    // the last line is expected to be an empty line - remove it 
    if (lines.length > 1 && lines[ lines.length - 1 ].trim() === '') { 
     lines.pop(); 
    } 

    // how much white-space do we need to remove form each line? 
    offset = lines[ 0 ].match(/^\s*/)[ 0 ].length; 

    // remove the exess white-space from the beginning of each line 
    lines = lines.map(function (line) { 
     return line.slice(offset); 
    }); 

    // set this new content to the PRE element 
    $(this).text(lines.join('\n')); 
}); 

現場演示:http://jsfiddle.net/pjEYm/3/

雖然這個作品,我還是寧願某種CSS解決方案。有一個嗎?

+1

你的問題是我的解決方案。 – pilau 2014-09-04 22:19:41

回答

3

沒有CSS的解決方案;但是,你可以設置pre元素陰性切緣的意義,但那麼你就需要使用一個固定的數目和ch單元(這是沒有得到普遍支持)來設置它。這將是相當笨拙和僵化和不可靠的。

pre元素意味着預格式化文本,你不應該使用它,除非你真的想要的。對於程序代碼,您可以只使用強制換行符(<br>)和領先的不間斷空格進行縮進(理論上,不可靠,但在實踐中可行)。然而最簡單,最安全的,只包含數據要顯示爲預設置,即使它傷了HTML (這是利益只有誰讀它的人少)的佈局。