innerhtml
  • html
  • 2011-08-25 141 views 1 likes 
    1

    作爲問題,這些跨度元素在瀏覽器中顯示兩種樣式,爲什麼?爲什麼在使用innerHTML時兩個span元素之間沒有間距?

    <html> 
        <head> 
        <title></title> 
        <script type="text/javascript"> 
        function loadHTML() { 
         var html = '<span class="edited-box">sfds</span><span class="added-box">sfds</span>'; 
         document.getElementById('content').innerHTML = html; 
        } 
        </script> 
        </head> 
        <body> 
        <div style="background-color:#ccc;" onclick="loadHTML();">click to add span</div> 
        <div id="content"></div> 
        <div> 
         <span class="edited-box">sfds</span> 
         <span class="added-box">sfds</span> 
        </div> 
        </body> 
    </html> 
    
    +0

    這兩者之間有什麼不同? – mwan

    回答

    4

    因爲兩個HTML span元素之間有空格。如果你寫的,比如,這樣,你會看到:

    <html> 
        <head> 
        <title></title> 
        <script type="text/javascript"> 
        function loadHTML() { 
         var html = '<div><span class="edited-box">sfds</span><span class="added-box">sfds</span></div>'; 
         document.getElementById('content').innerHTML = html; 
        } 
        </script> 
        </head> 
        <body> 
        <div style="background-color:#ccc;" onclick="loadHTML();">click to add span</div> 
        <div id="content"></div> 
        <div> 
         <span class="edited-box">sfds</span><span class="added-box">sfds</span> 
        </div> 
        </body> 
    </html> 
    

    <span>是一個內聯元素 - 也就是說,它沒有空間的上方,下方,或側面。爲了有空間,在Javascript將跨度之間添加&nbsp;這樣:

     var html = '<div><span class="edited-box">sfds</span>&nbsp;<span class="added-box">sfds</span></div>'; 
    
    +0

    我知道了它.inline元素是重點,有必要深入理解它。謝謝! – leotso

    2

    看那非換空間部分在這裏:http://www.w3schools.com/HTML/html_entities.asp

     
    "Browsers will always truncate spaces in HTML pages. If you write 10 spaces in 
    your text, the browser will remove 9 of them, before displaying the page. To add 
    spaces to your text, you "can use the &nbsp; character entity. 
    

    ,因爲它說,中任意數量的空格兩個span元素(或任何其他內聯元素)將被渲染爲單個空間。所以

     
    
    <span>sfds</span> 
    <span>sfds</span> 
     
    

    之間的換行符將呈現爲

     
    
    <span>sfds</span> <span>sfds</span> 
     
    

    (換行符被截斷爲單個空格。)

    在您的例子中,注意在HTML中是通過JavaScript添加到DOM中,span元素之間沒有空格,因此呈現方式不同。

    如果您需要兩者匹配,您可以a)修改您的HTML以匹配您在JS中注入到DOM中的HTML,或者b)在注入的兩個跨度之間使用不間斷的空格進入JS中的DOM。

    相關問題