首页 > 解决方案 > 填写文本时按钮奇怪地移动

问题描述

这就是错位所以,我想在网页上编写井字游戏,使用纯 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);
}

标签: javascripthtmlcsstic-tac-toe

解决方案


class game {
  fig = {x: "&#x2B55;", o: "&#x274C;"};
  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>


推荐阅读