[英]Simple JavaScript chess board
誰能給我一個關於如何使用 JavaScript、使用表格標簽或生成棋盤(8x8)的提示?
到目前為止,我有以下內容:
<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;"> </div>');
}
else
{
document.write('<div style="background-color:#000000;float:left;"> </div>');
}
}
else
{
document.write('<div style="background-color:#FFFFFF;float:left;"> </div>');
}
/*
*/
count++;
}
</script>
</body>
</html>
我嘗試將黑色和白色分別分配給每個奇數和偶數,但它不起作用。
先感謝您。
我現在無法測試它,但這應該有效。 此代碼創建一個 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);
在某些時候對我來說,這變成了代碼高爾夫:
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:
<div id="mainChessBoard">
</div>
CSS:
#mainChessBoard
{
width:160px;
height:160px;
border:1px solid black;
}
div
{
width:20px;
height:20px;
float:left;
}
這是構建棋盤的基本基礎。
您可以在控制台中查看棋盤圖案。
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)
你可以生成任何你想要的大小的板,這種方式很容易改變方塊的大小和顏色。 你不需要改變任何其他東西。
在樣式表上保持外觀是一種很好的做法。 也不要使用 document.write
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
#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;
}
可能你想用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>
以下代碼將僅使用 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>
你應該試試這個,這真的有用
<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>
我的想法很簡單,如果行是even
則從白塊開始,否則從黑塊開始。
HTML:
<div id="mainChessBoard"></div>
Javascript:
const fragment = document.createDocumentFragment();
const board = document.getElementById("mainChessBoard");
const size = 8;
for (let i = 0; i < size; i++) {
let start = i % 2 === 0 ? 0 : 1; // if row is even then start with white otherwise start with black;
for (let j = 0; j < size; j++) {
const div = document.createElement('div');
div.classList.add(start === 1 ? "black" : "white");
fragment.appendChild(div);
start = start === 1 ? 0 : 1;
}
}
board.appendChild(fragment);
一些現代化,使用css variables , css attr()和dataset attributes 。
這允許調整主題,並保持簡單。
const cols = {0:"A", 1:"B", 2:"C", 3:"D", 4:"E", 5:"F", 6:"G", 7:"H"} const table = document.createElement("table"); table.className = "board"; for (let i = 1; i < 9; i++) { let tr = document.createElement('tr'); tr.dataset.line = i for (let j = 1; j < 9; j++) { let td = document.createElement('td'); td.dataset.col = cols[j-1] td.dataset.line = i if (i%2 == j%2) { td.className = "white square"; } else { td.className = "black square"; } tr.appendChild(td); } table.appendChild(tr); } document.querySelector("div").appendChild(table);
:root { --size: 640px; --backcolor: darkslategray; --dark: grey; --light: white; --legend: azure; } .board { width: var(--size); height: var(--size); border: 32px solid; border-color: var(--backcolor); border-radius: 0.2rem; } .square { border: 1px black solid; } .white{ background: var(--light); } .black{ background: var(--dark) } .board tr::before { content: attr(data-line); position: absolute; margin: 1.8rem 0 0rem -1.5rem; font-size: larger; color: var(--legend); } .board tr::after { content: attr(data-line); position: absolute; margin: 1.8rem 0 0rem 0.8rem; font-size: larger; color: var(--legend); } .board tr:first-child > td::before { content: attr(data-col); position: absolute; margin: -4rem 0 0rem 1.6rem; font-size: larger; color: var(--legend); } .board tr:last-child > td::after { content: attr(data-col); position: absolute; margin: 2.6rem 0 0rem 1.6rem; font-size: larger; color: var(--legend); }
<div></div>
這是一個普通的 JS 復制粘貼解決方案。 我知道它在調節方面不是那么干凈,但它可以理解地完成這項工作,而且非常簡單。 字段大小也很容易調整。
const fieldSize = 50; const whiteField = document.createElement("div"); whiteField.style = `height:${fieldSize}px;width:${fieldSize}px;background-color:white;display:inline-block`; const blackField = document.createElement("div"); blackField.style = `height:${fieldSize}px;width:${fieldSize}px;background-color:black;display:inline-block`; for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) i % 2 === 0 ? j % 2 === 0 ? document.body.appendChild(blackField.cloneNode(true)) : document.body.appendChild(whiteField.cloneNode(true)) : j % 2 === 0 ? document.body.appendChild(whiteField.cloneNode(true)) : document.body.appendChild(blackField.cloneNode(true)); document.body.appendChild(document.createElement("br")); }
我們總能想到更好的性能,這里是使用documentFragments的 DOM 優化解決方案——
// main container let container = document.querySelector("#main"); // a fragment object to store a 2-D mesh of rows and columns let fragment = new DocumentFragment(); for (let i = 0; i < 8; i++) { // a fragment object to store a single row with 8 columns let rowFragment = new DocumentFragment(); for (let j = 0; j < 8; j++) { // div element for a column let col = document.createElement("div"); col.style.border = "1px solid"; if ((i + j) % 2 == 0) col.style.background = "black"; else col.style.background = "white"; // adding column in a document fragment rowFragment.appendChild(col); } // adding row in a main fragment fragment.appendChild(rowFragment); } // adding fragment to a DOM one time - this will update the DOM only once container.appendChild(fragment);
.container { display: flex; width: 416px; /* width + horizontal border of each cell ((50 + 2) * 8) */ height: 416px; /* height + vertical border of each cell ((50 + 2) * 8) */ } div { flex-wrap: wrap; /* to fit 8 cells in a row as per the width */ width: 50px; height: 50px; }
<div class="container" id="main"></div>
在這里,DocumentFragment 創建了我們添加的元素的 object,但它不是活動文檔樹的一部分,除非我們將它 append 到任何其他 DOM 節點。
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:
div {
float: left;
width: 20px;
height: 20px;
}
.first {
clear: left;
}
.black {
background: black;
}
.white {
background: red;
}
示例: http : //jsfiddle.net/YJnXG/2/
你的意思是這樣?
.... html.....
<table>
<tr>
<script language='javascript'>
<!--
alternate();
//-->
</script>
</tr>
</table>
....more html.....
function alternate()
{
var numOfCells = 6;
var num = 0;
for (i = 0; i < numOfCells ; i++)
{
txt = "<td bgColor='";
txt += (num % 2 == 0) ? 'red' : 'black';
txt += "'>"
document.write(txt);
num++;
}
}
% 符號是 mod; 它返回除法的余數。 這 ”(...) ? ... : ...;” 構造就像一個 if/else。 如果條件為真,則選擇第一個選項——否則選擇第二個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.