我已经从头开始使用JavaScript代码创建了一个3 * 3矩阵。
现在我想给它一个边框。我希望看到9个带有实线边框的正方形。
我正在考虑在循环中动态提供样式。
我不知道如何为具有唯一ID的div定义变量。
这是我的代码:
router.post('/login', passport.authenticate('local'), (req, res) => {
var token = authenticate.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, token: token, status: 'You are successfully logged in!'});
});
答案 0 :(得分:1)
您需要使用
获取dom document.getElementById
&添加样式
for (i = 1; i <= 4; i++) {
document.getElementById('div_' + i).style.border = '1px solid blue';
}
<div id="div_1">1</div>
<div id="div_2">2</div>
<div id="div_3">3</div>
<div id="div_4">4</div>
答案 1 :(得分:1)
这不是我会使用div的东西,因为它们没有提供语义含义,而且你正在创建表格数据。
我会改为使用专为此目的而设计的表格。
另外,直接对元素进行样式化通常被认为是不好的做法。这样做往往不是最好的CSS,所以你不要重复自己,并且能够轻松改变风格。
我写了一个示例,演示了使用这两个建议。
// Create a table and body
var table = document.createElement("table");
var body = document.createElement("tbody");
// Loop through the rows and columns to add items
var count = 1;
for (var i = 1; i < 4; i++) {
// Create a new row
var row = document.createElement("tr");
for (var j = 1; j < 4; j++) {
var cell = document.createElement("td");
cell.id = count++; // Set the id
cell.innerHTML = cell.id; // Set innerHTML to show number for example
row.appendChild(cell); // Add the cell to the row
}
body.appendChild(row); // Add the row to the body
}
// Add the body to the table and the table to the document
table.appendChild(body);
document.body.appendChild(table);
&#13;
table {
border: 1px solid blue;
/* Add the border to the whole table */
border-left-width: 0;
/* But no border on the left hand side */
border-collapse: separate;
/* Ensure borders are visible */
border-spacing: 0;
/* But with no spaces */
}
table td {
border-left: 1px solid blue;
/* Add internal borders to cells */
border-top: 1px solid blue;
}
tbody tr:first-child td {
border-top: none;
/* Make sure we don't have a double border on top */
}
&#13;
答案 2 :(得分:0)
只需从父元素中选择一些特定的选择器。或者在所有正方形中添加一个类。
我认为你正在尝试这样做:
#div_main {
height: 90px;
width: 90px;
}
#div_main div{
height: 30px;
width:90px;
display: flex;
margin:0;
}
#div_main div div{
height:30px;
width:30px;
border: 1px black solid;
margin:0;
}
<div id=div_main>
<div id=div_1>
<div id=div_1_1> </div>
<div id=div_1_2> </div>
<div id=div_1_3> </div>
</div>
<div id=div_2>
<div id=div_1_1> </div>
<div id=div_2_2> </div>
<div id=div_3_3> </div>
</div>
<div id=div_3>
<div id=div_3_1> </div>
<div id=div_3_2> </div>
<div id=div_3_3> </div>
</div>