使用JavaScript和DOM创建棋盘模式

使用JavaScript和DOM创建棋盘模式

使用JavaScript和文档对象模型(DOM)可以非常容易地创建棋盘模式。使用这种方法,您可以通过调整一些参数来创建任意行数和列数的棋盘。而且,使用这种方法写的代码行数将远远少于使用纯HTML和CSS创建相同棋盘的代码行数,特别是当行数和列数非常大时。

步骤: 创建一个嵌套的for循环。我们把外层循环称为“i”,内层循环称为“j”。外层循环用于创建行,而内层循环用于在每一列中创建单元格。通过这样做,将创建N*M个单元格,其中N是行数,M是列数。内层循环中i和j的组合可以用来区分所生成的每个单元格。循环结束时,我们将得到一个创建的表格。此外,我们需要用适当的颜色为单元格上色。如果i和j的和是偶数,则单元格必须被涂成白色,否则涂成黑色。这将在棋盘上创建黑白相间的单元格。可以使用DOM创建表格和表格单元格,可以使用CSS为单元格上色。

下面是上述方法的实现。

示例:

HTML

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>Chess board</title> 
</head> 
  
<body> 
    <span style="color:green; font-size:30px;"> 
        GeeksforGeeks 
    </span> 
    <br><br> 
  
    <script type="text/javascript"> 
  
        // Create a center tag to center all the elements 
          
    </script> 
</body> 
  
</html> 

CSS

body { 
  text-align: center; 
} 
  
.cell { 
  height: 30px; 
  width: 30px; 
  border: 1.5px solid grey; 
  border-style: inset; 
} 
  
.blackcell { 
  background-color: black; 
} 
  
.whitecell { 
  background-color: white; 
}

Javascript

var center = document.createElement('center'); 
  
// Create a table element 
var ChessTable = document.createElement('table'); 
for (var i = 0; i < 8; i++) { 
  
    // Create a row 
    var tr = document.createElement('tr'); 
    for (var j = 0; j < 8; j++) { 
  
        // Create a cell 
        var td = document.createElement('td'); 
  
        // If the sum of cell coordinates is even 
        // then color the cell white 
        if ((i + j) % 2 == 0) { 
  
            // Create a class attribute for all white cells 
            td.setAttribute('class', 'cell whitecell'); 
            tr.appendChild(td); 
        } 
  
        // If the sum of cell coordinates is odd then 
        // color the cell black 
        else { 
  
            // Create a class attribute for all black cells 
            td.setAttribute('class', 'cell blackcell'); 
  
            // Append the cell to its row 
            tr.appendChild(td); 
        } 
    } 
  
    // Append the row 
    ChessTable.appendChild(tr); 
} 
center.appendChild(ChessTable); 
  
// Modifying table attribute properties 
ChessTable.setAttribute('cellspacing', '0'); 
ChessTable.setAttribute('width', '270px'); 
document.body.appendChild(center);

输出:

使用JavaScript和DOM创建棋盘模式

代码解释: 上述代码将创建一个8×8的棋盘。然而,只需修改i和j的终止条件,我们就可以轻松创建一个N×M的棋盘。使用Javascript DOM,首先使用createElement()创建一个table元素。我们知道i循环用于创建行,因此每次迭代期间都会创建一个行元素。同样,j循环负责创建单元格。因此,每次迭代期间都会创建表格单元格。如前所述,每个单元格的颜色可以通过i和j值的求和来决定。如果总和是偶数,则单元格必须为白色;如果是奇数,则单元格必须为黑色。这是通过使用setAttribute()创建并分配适当的class属性来完成的,然后使用CSS根据需要分配正确的颜色、大小和其他属性。最后,所有元素都被添加到HTML文档的body中。因此,我们可以非常容易地使用javascript和DOM创建一个简单的棋盘图案。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程