【问题标题】:How to add text above grid cells?如何在网格单元格上方添加文本?
【发布时间】:2020-07-16 16:27:06
【问题描述】:

这里是 js 新手。我想用靠近棋盘边缘的数字和字母标记我的棋盘。但是,我找不到这样做的抽象方法。到目前为止,我只有用颜色创建的棋盘(未显示)。

HTML:

<div id = 'gridcontainer'> 

</div>

Javascript:

function makeChessBoard(row, col)           //creates 64 cells
        {
            grid = document.getElementById('gridcontainer');
            grid.style.cssText = "grid-template-columns: repeat(" + col + ", 60px);

            cell = [];
            for (i = 0; i < (row * col); i++)
            {
                cell[i] = document.createElement('div');
                cell[i].className = 'cells';

                grid.appendChild(cell[i]);
            }
        }
makeChessBoard(8, 8);

CSS:

#gridcontainer
{
    display: grid;
    grid-gap: 0;
}

拜托,非常感谢任何帮助!

【问题讨论】:

    标签: javascript html css dynamic css-grid


    【解决方案1】:

    最好将你的单元阵列设为 2d。您可以使用“if”制作 +1 行和列,并在其中输入数字和字母。然后添加他们特殊的类。类似的东西。

    function makeChessBoard(row, col){           //creates 64 cells
      grid = document.getElementById('container');
      grid.style.cssText = "grid-template-columns: repeat(" + col + ", 60px)"
      const leters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
      cell = [];
      for (i=0; i<row+1; i++) {
        for(j=0; j<col+1; j++) {
          cell[i][j] = document.createElement('div');
          cell[i][j].className = 'cells';
          if(cell[i][col]) {
            this.innerText = leters[j]
          }
          if(cell[row][j]) {
            this.innerText = j+1
          }
          grid.appendChild(cell[i][j]);
        }
      }
    }
    

    【讨论】:

    • 您好,欢迎来到 S/O - 感谢您的积极贡献! :) 请考虑扩展您的答案,以解释为什么您的选择会更好。 How do I write a good answer? 也很值得一读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2013-04-20
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多