javascript - 填写文本时按钮奇怪地移动
问题描述
这就是错位所以,我想在网页上编写井字游戏,使用纯 JavaScript、HTML 和 CSS。我做了一些逻辑,所以板子可以根据数组中的条目进行更新,但是当我这样做时,按钮不再排成一行,而且看起来很糟糕。预期结果:文本被填充到按钮中,按钮保留在其位置。实际结果:文本被填充,但按钮向下移动。HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="scripts.js"></script>
<title>My Website</title>
</head>
<body>
<div id="board">
<div id="row1">
<button class="field"> </button>
<button class="field"> </button>
<button class="field"> </button>
</div>
<div id="row2">
<button class="field"> </button>
<button class="field"> </button>
<button class="field"> </button>
</div>
<div id="row3">
<button class="field"> </button>
<button class="field"> </button>
<button class="field"> </button>
</div>
</div>
</body>
</html>
CSS:
.field{
display: inline-block;
border-style: solid;
background-color: white;
height: 100px;
width: 100px;
font-size: 10px;
}
#board {
margin-left: 40%;
margin-top: 20%;
height: 50%;
}
JS:
function game() {
this.board = [
" ", "x ", " ",
" ", " ", " ",
" ", " ", " x"
]
this.printBoard = function(buttons) {
for(i = 0; i < buttons.length; i++) {
buttons[i].innerHTML = this.board[i];
}
}
}
window.onload = function() {
let buttons = document.getElementsByClassName("field");
let myGame = new game();
myGame.printBoard(buttons);
}
解决方案
class game {
fig = {x: "⭕", o: "❌"};
board = Array(9).fill("");
el = document.querySelector("#board");
constructor() {
this.printBoard();
}
printBoard(){
this.el.innerHTML = this.board.reduce((h, f) => h + `<button>${this.fig[f]||""}</button>`, "");
}
};
const myGame = new game();
myGame.board[0] = "x";
myGame.board[8] = "o";
myGame.printBoard();
#board {
display: flex;
flex-flow: row wrap;
width: 50vh;
height: 50vh;
}
#board > button {
flex-grow: 1;
--margin: 0vh; /* Set a desired value */
width: calc(33.333% - var(--margin) * 2);
margin: var(--margin);
border: 0;
box-shadow: 0 0 0 0.5px #000;
background-color: white;
font-size: 10vh;
line-height: 0;
cursor: pointer;
transition: background 0.3s;
}
#board > button:hover {
background: #0bf;
}
<div id="board"></div>
推荐阅读
- python - 使用 Python 中的列表推导将嵌套列表中的第二个值与第一个值相加
- typescript - 无法实例化 ColDef 变量
- lua - 如何制作一个lua文件?
- java - 如何使用来自 maven 的标签执行黄瓜功能?
- javascript - 数组在它应该更新之前
- python - 当我单击一个按钮以移动到 pygame、python 中的另一个屏幕时,我需要帮助清除菜单
- angular - 属性网格的角度反应形式
- flutter - sqfentity 在每个运行的应用程序上初始化数据库
- amazon-web-services - Gremlin 中每个节点的广度优先限制?
- javascript - 当我尝试在 React 中使用 WebXR 时,我不断看到“无法在 'XRSystem' 上执行 'requestSession':已经有一个活动的、身临其境的 XRSession”