如何在元素后面添加空格

How to append a space after an element

本文关键字:添加 空格 元素      更新时间:2023-09-26

我想知道如何在JavaScript中添加元素后的空间?我在for循环中创建了一个图像和一个span,我想在图像和span之后添加一个空格。下面是我创建标签的方法:

var image = document.createElement("img");
var host = document.createElement ("div");
host.appendChild (document.createElement ("img"));
host.appendChild (document.createTextNode (" "));
host.appendChild (document.createElement ("span"));
console.log (host.innerHTML);

输出
<img /> <span></span>

您可以通过在imgspan上使用CSS属性margin来实现相同的视觉外观。

既然你要求一些视觉空白-最简单和最灵活的方法是通过CSS应用它,而不是使用空格字符:

img {
    margin-right: 5px;
}

如果你只想把它应用到你创建的特定元素上,你可以使用JavaScript应用CSS: http://jsfiddle.net/aRcPE/.

image.style.marginRight = "5px"; // "foo-bar" becomes "fooBar" since
                                 // the hyphen is not allowed in this notation

试试document.createTextNode(" ");