我想做的是使用循环和数组通过 JavaScript 生成 HTML。我目前正在尝试(并遇到问题)的是我的第二个专栏。我有一系列类(class)被放置在输入复选框中,然后是标签。从那里我使用 if 语句在每第二次迭代后添加中断以创建我的列。我的问题是让第二列垂直对齐。我只想使用 JS 而不是 CSS 来完成它,但我对两者都持开放态度。
由于我的问题有多个部分,我不确定要使用什么关键字来缩小我在循环中使用 .createElement 来对齐列的搜索范围,以创建 2 列并在 JavaScript 中垂直对齐它们,所以如果这是在另一个地方回答,欢迎留言。
这是相关代码。
HTML
<body>
<section id="wrapper">
<form action="POST" novalidate="novalidate">
<fieldset id="contactInfo">
<legend>Contact Info</legend>
<label>Name: </label>
<input type="text" placeholder="John" required autofocus /><br>
<label>Email: </label>
<input type="email" name="email" placeholder="galacticDonut@yahoo.com" required /><br>
<label>Age: </label>
<select></select>
</fieldset>
<fieldset id="Programs">
<legend>Programs</legend>
<ul></ul>
</fieldset>
</form>
JavaScript
//************************
//Generate course options list
function generateCourses() {
var courseOptions = ["CSCI","CSIA","DBMS","INFA","ITSP","NETI","SDEV","SVAD"]
courseOptions.sort();
var uList = document.getElementsByTagName("ul")[0];
for (var i=0; i<courseOptions.length; i++) {
//Create inputs
var labels = document.createElement("label");
labels.innerHTML = courseOptions[i];
var inputs = document.createElement("input");
inputs.setAttribute("type", "checkbox");
//Set input value
inputs.value = courseOptions[i];
//Set input text
inputs.text = courseOptions[i];
//Put input in UL
uList.appendChild(inputs);
//place label in ul after checkboxes
uList.appendChild(labels)
if (i % 2) {
var breakLine = document.createElement("br");
uList.appendChild(breakLine);
}//End if
}//End for loop
} //End generateCourses function
最佳答案
我稍微修改了你的代码:
https://jsfiddle.net/gat4vo9p/7/
添加了一个 li
里面的元素ul
.每个li
表现得像表格行。
ul {
list-style: none;
position: relative;
}
li {
display: table;
width: 100%;
height: 30px;
vertical-align: middle;
}
li > span {
display: table-cell;
width: 50%;
}
还添加了 <label for
属性。因此,点击标签也会标记/取消标记复选框。
关于javascript - 如何在 JavaScript(或 CSS)中平均对齐使用循环、数组和附加子项创建的两个垂直列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39947823/