简体   繁体   English

尝试使用香草JS将换行符插入HTML

[英]Trying to insert line break into HTML with vanilla JS

I've been coding with JavaScript for a while now and I just started using the features for adding HTML elements through JavaScript and I have a button that adds two input fields each time it's pressed. 我使用JavaScript进行编码已有一段时间,我刚刚开始使用通过JavaScript添加HTML元素的功能,并且有一个按钮,每次按下该按钮时都会添加两个输入字段。 The first time the user presses the button I want the element pushed down 250px from the top, and each time have about 20px spacing, but instead of that, well you'll see when you run the code. 用户第一次按下按钮时,我希望元素从顶部向下推250px,每次间隔约20px,但是,相反,您会在运行代码时看到。 This question not the same as append many elements because its not my real issue, my real issue is trying to get each pair of input values separated by 20px from the other one each time the button is pressed. 这个问题与追加许多元素不同,因为这不是我的真正问题,我的真正问题是每次按下按钮时都试图使每对输入值与另一对输入值相隔20px。

 let addN = document.getElementById("adda"); let margin = 250; addN.addEventListener("click", () => { let newCoordsX = document.createElement('input'); let newCoordsY = document.createElement('input'); newCoordsX.placeholder = "X value"; newCoordsY.placeholder = "Y value"; newCoordsX.style.marginTop = margin + "px"; document.body.appendChild(newCoordsX); document.body.appendChild(newCoordsY); }); 
 #adda { position:absolute; top:140px; /*left:-1300px;*/ left: 0px; width:180px; height:40px; padding:5px; background-color:rgb(171, 202, 252); border-radius:15px; } #add { position:absolute; color:white; font-weight:bold; font-size:21px; left:14px; top:10px; } #adda:hover{ cursor:pointer; background-color:rgb(191, 215, 252); } 
 <div id="adda"> <div id="add">Add another node</div> </div> 

You can change the display of inputs to block 您可以将输入的display更改为block

 let addN = document.getElementById("adda"); let margin = 250; addN.addEventListener("click", () => { let newCoordsX = document.createElement('input'); let newCoordsY = document.createElement('input'); newCoordsX.placeholder = "X value"; newCoordsY.placeholder = "Y value"; newCoordsX.style.marginTop = margin + "px"; newCoordsX.style.display = "block" newCoordsY.style.display = "block" document.body.appendChild(newCoordsX); document.body.appendChild(newCoordsY); }); 
 #adda { position:absolute; top:140px; /*left:-1300px;*/ left: 0px; width:180px; height:40px; padding:5px; background-color:rgb(171, 202, 252); border-radius:15px; } #add { position:absolute; color:white; font-weight:bold; font-size:21px; left:14px; top:10px; } #adda:hover{ cursor:pointer; background-color:rgb(191, 215, 252); } 
 <div id="adda"> <div id="add">Add another node</div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM