为什么使用innerHTML时两个span元素之间没有间距?
那么问题来了,这些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>
As the question, these span elements display with two style in browser, why?
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为两个 HTML span 元素之间有空格。例如,如果您像这样编写它,您会看到:
是一个内联元素 – 也就是说,它的上方、下方或两侧没有空间。要留出空间,请在 Javascript 中的跨度之间添加
Because there's whitespace between the two HTML span elements. If you wrote it, for instance, like this, you'd see:
<span>
is an inline element – That is, it has no space above, below, or to the sides. To have space, add请查看此处的不间断空格部分: http://www.w3schools.com/HTML/html_entities .asp
正如它所说,两个
span
元素(或任何其他内联元素)之间的任何数量的空白都将呈现为单个空格。因此,之间的换行符将呈现为
(换行符被截断为单个空格。)
在您的示例中,请注意,在通过 JavaScript 添加到 DOM 的 html 中,
span< 之间没有空格/code> 元素,因此它的渲染方式有所不同。
如果您需要两者匹配,您可以 a) 修改 HTML 以匹配您在 JS 中注入 DOM 的 HTML,或者 b) 在您注入 DOM 的两个跨度之间使用不间断空格JS。
Look at the Non-Breaking Space section here: http://www.w3schools.com/HTML/html_entities.asp
As it says, any amount of white space between two
span
elements (or any other inline elements) will be rendered as a single space. So the line break betweenwill be rendered as
(The line break is truncated to a single space.)
In your example, notice that in the html that is added to the DOM via JavaScript, there are no spaces between the
span
elements, so it is rendered differently.If you need the two to match, you can either a) modify your HTML to match the HTML that you are injecting into the DOM in the JS or b) use a non-breaking space between the two spans you are injecting into the DOM in the JS.