innerhtml
  • html
  • 2011-08-25 33 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。

    相关问题