提问者:小点点

使用js和dom appendChild添加输入标记似乎没有空白处


当我在js脚本中使用DOMappendchild()添加输入标记时,它们似乎没有空白处,因为它们之间没有分隔。 在html文件中写入的输入标记具有这种分隔。 元素检查器说它们都有相同的样式。

js脚本:

document.body.appendChild(document.createElement("input"));

我不知道如何谷歌这个问题,所以我在这里问,怎么回事,我如何在js脚本中解决这个问题?


共3个答案

匿名用户

添加一个空白或给一个带边距的类

null

// without
document.body.appendChild(document.createElement("input"));
document.body.appendChild(document.createElement("input"));

document.body.appendChild(document.createElement("hr"));

// with whitespace

document.body.appendChild(document.createElement("input"));
document.body.appendChild(document.createTextNode(" "));
document.body.appendChild(document.createElement("input"));

document.body.appendChild(document.createElement("hr"));

// with css
const input = document.createElement("input");
input.classList.add("spaced")
document.body.appendChild(input);
document.body.appendChild(input.cloneNode(1));
.spaced { margin-right:5px; }

匿名用户

您可以按如下方式添加边距:

null

let inp = document.createElement("input");
inp.style.margin='4px';
document.body.appendChild(inp);
inp = document.createElement("input");
inp.style.margin='4px';
document.body.appendChild(inp);

匿名用户

输入之间的空格不是边距,它可能是白色空格,因此当您添加一个带有js的元素时,附加的是不带空格的,如果您使用样式为font-size:0的div来包装两个输入,即使是在html中添加的输入,也会看到空格消失