javascript 如何在元素后附加一个空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8562843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:49:29  来源:igfitidea点击:

How to append a space after an element

javascripthtml

提问by Sameh Farahat

I was wondering how can I append a space after an element in JavaScript? I am creating an image and a span in for loop, and I want to append a space after the image and after the span. Here is how I create the tags:

我想知道如何在 JavaScript 中的元素后附加一个空格?我正在 for 循环中创建一个图像和一个跨度,我想在图像和跨度之后附加一个空格。这是我创建标签的方法:

var image = document.createElement("img");

回答by Filip Roséen - refp

var host = document.createElement ("div");

host.appendChild (document.createElement ("img"));
host.appendChild (document.createTextNode (" "));
host.appendChild (document.createElement ("span"));

console.log (host.innerHTML);

output

输出

<img /> <span></span>


You can achieve the same visual appearance by using the CSS property marginon either the imgor span.

您可以margin通过在img或上使用 CSS 属性来获得相同的视觉外观span

回答by pimvdb

Since you asked for some visual whitespace - the simplest and most flexible way is applying it through CSS, not using a space character:

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

img {
    margin-right: 5px;
}

If you want to only apply it to the specific element you create, you can use JavaScript to apply the CSS: http://jsfiddle.net/aRcPE/.

如果您只想将其应用于您创建的特定元素,您可以使用 JavaScript 来应用 CSS:http: //jsfiddle.net/aRcPE/

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

回答by Parzifal

Try document.createTextNode(" ");

尝试 document.createTextNode(" ");