Html 简单的 JavaScript 棋盘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16684004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:40:34  来源:igfitidea点击:

Simple JavaScript chess board

javascripthtmlcss

提问by Tyrant

Could anyone give me a hint on how to generate a chess board (8x8) using JavaScript, using a table tags or ?

谁能给我一个关于如何使用 JavaScript 生成棋盘(8x8)的提示,使用表格标签或?

I've got the following so far:

到目前为止,我有以下内容:

<DOCTYPE html>
<html>
<head>
<style>

div
{
border:1px solid black;
width:20px;
height:20px;
}

</style>
</head>
<body>
<script type="text/javascript">

    // create a chess table 8x8.

    var count = 0;

while (count < 64)
    {

    if (count % 2 == 0)

        {

        if (count % 8 == 0 && count !=0)
            {
            document.write('<br/><div style="background-color:#000000;float:left;">&nbsp</div>');

            }
        else    
            {
            document.write('<div style="background-color:#000000;float:left;">&nbsp</div>');    
            }
        }

    else

        {
        document.write('<div style="background-color:#FFFFFF;float:left;">&nbsp</div>');
        }
    /*  
    */          
    count++;
    }
</script>

</body>
</html>

I tried to assign black and white to each odd and even number respectively, but it doesn't work this way.

我试图分别为每个奇数和偶数分配黑色和白色,但这种方式不起作用。

Thank you in advance.

先感谢您。

回答by Alfonso Jiménez

I can not test it at this moment but this should work. This code creates a 8x8 table in which black cells are tagged with "black" class and white cells are tagged with "white" class. Use CSS to give them color. I hope it helps.

我现在无法测试它,但这应该有效。此代码创建一个 8x8 表,其中黑色单元格标记为“黑色”类,白色单元格标记为“白色”类。使用 CSS 赋予它们颜色。我希望它有帮助。

var table = document.createElement("table");
for (var i = 1; i < 9; i++) {
    var tr = document.createElement('tr');
    for (var j = 1; j < 9; j++) {
        var td = document.createElement('td');
        if (i%2 == j%2) {
            td.className = "white";
        } else {
            td.className = "black";
        }
        tr.appendChild(td);
    }
    table.appendChild(tr);
}
document.body.appendChild(table);

回答by aquinas

At some point for me, this became code golf:

在某些时候对我来说,这变成了代码高尔夫:

http://jsfiddle.net/4Ap4M/

http://jsfiddle.net/4Ap4M/

JS:

JS:

for (var i=0; i< 64; i++){
    document.getElementById("mainChessBoard").appendChild(document.createElement("div")).style.backgroundColor = parseInt((i / 8) + i) % 2 == 0 ? '#ababab' : 'white';    
}

HTML:

HTML:

<div id="mainChessBoard">
</div>

CSS:

CSS:

#mainChessBoard
{
    width:160px;
    height:160px;
    border:1px solid black;
}

div
{
 width:20px;
 height:20px;
 float:left;
}

回答by user3449311

This is the basic foundation to build your chess board.
You can check out the chess board pattern in the console.

这是构建棋盘的基本基础。
您可以在控制台中查看棋盘图案。

   var chessBoard = function(size){
    var hash = '#'
    var space = '_'
    for (var i = 0; i < size; i++) 
    {        

        hash += '\n'

        for (var j = 0; j < size; j++) 
        {
        if((i +j) % 2 == 0)
        {
        hash  += space
        }
        else
        {
        hash  += "#"
        }
    };

};

console.log(hash)
}(8)

回答by Vitim.us

You can generate boards of any size you want, and this way is pretty easy to change the size of the squares and the colors. you don't need to change anything else.

你可以生成任何你想要的大小的板,这种方式很容易改变方块的大小和颜色。你不需要改变任何其他东西。

It is good practice to keep appearance on the stylesheet. Also don't use document.write

在样式表上保持外观是一种很好的做法。也不要使用 document.write

http://jsfiddle.net/YEJ9A/1/

http://jsfiddle.net/YEJ9A/1/

Javascript

Javascript

var x=8;
var y=8;

var chessBoard = document.getElementById("chessBoard");

for (var i=0; i<y; i++){
    var row = chessBoard.appendChild(document.createElement("div"));
    for (var j=0; j<x; j++){
        row.appendChild(document.createElement("span"));
    }
}

CSS

CSS

#chessBoard span{
    display: inline-block;
    width: 32px;
    height: 32px;
}

#chessBoard div:nth-child(odd) span:nth-child(even),
#chessBoard div:nth-child(even) span:nth-child(odd){
    background-color: black;
}
#chessBoard div:nth-child(even) span:nth-child(even),
#chessBoard div:nth-child(odd) span:nth-child(odd){
    background-color: silver;
}

回答by Sodhi saab

May be you want to do it with divs, not with the table. So here is the solution for it.

可能你想用 来做divs,而不是用桌子。所以这是它的解决方案。

$(document).ready(function() {
  for (var i = 1; i <= 8; i++) {
    var divRow = $("<div>", {
      class: "row",
    });
    for (var j = 1; j <= 8; j++) {
      var div = $("<div>", {
        class: "square"
      });

      if (i % 2 == j % 2) {
        $(div).addClass("white");
      } else {
        $(div).addClass("black");
      }
      divRow.append(div);
    }
    $("#board").append(divRow);
  }
});
#board {
  margin: 0;
  width: 256px;
  height: 256px;
  border: solid 1px #333;
}

#board .row {
  margin: 0;
}

.square {
  height: 32px;
  width: 32px;
  background: #efefef;
  float: left;
}

.square.white {
  background: #fff;
}

.square.black {
  background: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="board"></div>

回答by Kumar Ajay A.K

You should try this one this will really work

你应该试试这个,这真的有用

<DOCTYPE html>
<html>

<head>
    <style>
        .chessBoard {
            display: inline-block;
            border: 2px solid lightGray;
        }

        .chessBoard div {
            line-height: 1px;
        }

        .chessBoard span {
            display: inline-block;
            width: 32px;
            height: 32px;
            background-color: snow;
        }
    </style>
</head>

<body>
    <div class="chessBoard" id="chessBoardNormal"></div>
    <div class="chessBoard" id="chessBoardRandom"></div>
    <script>
        function colorNormal(x, y, color) {
            var chessBoard = document.getElementById("chessBoardNormal");
            for (var i = 0; i < x; i++) {
                var row = chessBoard.appendChild(document.createElement("div"));
                for (var j = 0; j < y; j++) {
                    var span = document.createElement('span');
                    if (i & 1) { // odd
                        if (j & 1) { // white

                        } else { // black
                            span.style.backgroundColor = color;
                        }
                    } else { // even
                        if (j & 1) { // black
                            span.style.backgroundColor = color;
                        }
                    }

                    row.appendChild(span);
                }
            }
        }

        function colorRandom(x, y) {
            colorNormal(8, 8, Math.random() > .5 ? 'black' : '#CFD65C');
        }

        function getRandomHexColor() {
            return '#' + Math.floor(Math.random() * 16777215).toString(16);
        }

        colorNormal(8, 8, 'black');
    </script>
</body>

</html>

回答by NachuArun

The following code will print chess board using only HTML and JavaScript.

以下代码将仅使用 HTML 和 JavaScript 打印国际象棋棋盘。

<script>
    document.write("<table border='1' width='200' height='200'>");
    for(var i=1; i<=8; i++)
    {
    document.write("<tr>");
    for(var j=1; j<=8; j++)
    {
    if((i+j)%2!=0)
    {
    document.write("<td bgcolor='white'></td>");
    }
    else
    {
    document.write("<td bgcolor='black'></td>");
    }
    }
    document.write("</tr>");
    }
    document.write("</table>");
    </script>

回答by Igor Jerosimi?

Javascript:

Javascript:

var i, j, clas;
for (i = 0; i < 8; i++) {
    for (j = 0; j < 8; j++) {
        clas = '';

        if (j === 0) clas = 'first ';
        else if (j === 7) clas = 'last ';
        clas += (i % 2 == j % 2) ? 'white' : 'black';

        var field = document.createElement('div');
        field.className = clas;
        document.body.appendChild(field);
    }
}

CSS:

CSS:

div {
    float: left;
    width: 20px;
    height: 20px;
}
.first {
    clear: left;
}
.black {
    background: black;
}
.white {
    background: red;
}

Sample: http://jsfiddle.net/YJnXG/2/

示例:http: //jsfiddle.net/YJnXG/2/

回答by Glen Morse

You mean like this?

你的意思是这样?

.... html.....
&lt;table&gt;
&lt;tr&gt;
&lt;script language='javascript'&gt;
&lt;!--
alternate();
//--&gt;
&lt;/script&gt;
&lt;/tr&gt;
&lt;/table&gt;
....more html.....

function alternate()
{
var numOfCells = 6;
var num = 0;
for (i = 0; i &lt; numOfCells ; i++)
{
txt = "&lt;td bgColor='";
txt += (num % 2 == 0) ? 'red' : 'black';
txt += "'&gt;"
document.write(txt);
num++;
}
}

The % sign is mod; it returns the remainder of a division. the "(...) ? ... : ...;" construction is like an if/else. If the condition is true, the first option -- else the second.

% 符号是 mod; 它返回除法的余数。这 ”(...) ? ... : ...;” 构造就像一个 if/else。如果条件为真,则选择第一个选项——否则选择第二个。