我正在创建一个数独游戏板,我需要画一些线来划分 3x3 的盒子。该板是由按钮组成的,所以我想做的是更改第三列和第六列和行上按钮的边框颜色。
我面临的问题是我无法在按钮上添加 2 个边框:右侧和底部。 Js 代码使用 elem.setAttribute
一次仅添加一个属性。所以我尝试了一个据说可以让您添加多个属性的函数,但它似乎不起作用。
问题在哪里?
function createGameboard() {
var gameboard = document.getElementById("gameboard");
console.log("creating buttons");
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
var button = document.createElement("button");
button.id = i + "-" + j;
button.className = "buttons";
button.innerHTML = i + "-" + j;
if (i == 3 || i == 6) {
button.setAttribute("style", "border-bottom: 4px solid black");
}
if (j == 3 || j == 6) {
button.setAttribute("style", "border-right: 4px solid black");
}
if (
(i == 3 && j == 3) ||
(i == 6 && j == 6) ||
(i == 3 && j == 6) ||
(i == 6 && j == 3)
) {
setAttributes(button, {
"border-right": "4px solid black",
"border-bottom": "4px solid black",
});
}
gameboard.appendChild(button);
}
}
}
createGameboard();
function setAttributes(el, attrs) {
for (var key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
body {
background-color: #0f4c5c;
}
h1,
h5 {
color: white;
}
.sudoku #gameboard {
width: 40vmin;
height: 40vmin;
display: grid;
grid-template-columns: repeat(9, 1fr);
gap: 0;
}
.sudoku button {
width: 10vmin;
height: 10vmin;
background: white;
border: 3px solid gray;
margin: 0;
}
<body>
<div class="container">
<div class="col">
<h1 class="row mx-auto my-3" id="title">
Sudoku
</h1>
<div class="row my-2 container sudoku">
<div class="gameboard" id="gameboard"></div>
</div>
</div>
</div>
</div>
</body>
最佳答案
如果您仅使用 setAttribute
进行样式设置,则可以像这样修复它:
function setAttribute(element, key, value) {
element.style[key] = value
}
setAttribute(document.body, "backgroundColor", "red")
请注意,您需要使用 javascript 版本的样式(backgroundColor 而不是背景颜色)。
关于javascript - 如何在同一个元素上设置多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70774545/