想象一下我们要实现connect 4 game,问题是我实现了显示grid
的棋盘游戏。每当用户单击每一列时,木板珠应通过动画放置在木板中。
这是我的实现方式:
function selected(j) {
return function () {
console.log(`You clicked on column ${j}`);
// bead in the map :)
for (var i = gameSize[0] - 1; i > -1 ; i--){
if (map[i][j] == 0){
console.log(currentTurn)
if (i == 0){
availableCol.splice(availableCol.indexOf(j), 1);
}
if (currentTurn == "red"){
map[i][j] = 1;
changeColor(i, j)
break;
}
else {
map[i][j] = -1;
changeColor(i, j)
break;
}
}
}
console.log(availableCol)
// Check for the winner
// change turn
return changeTurn(currentTurn);
}
}
function changeColor(i, j){
var div = document.querySelector(`.cell-${i}-${j}`);
var newDiv = document.createElement('div');
div.style.backgroundColor = currentTurn;
var style = document.querySelector('style');
var keyframe = `\
@keyframes animation-${i}-${j} {\
0% {\
top: 0%;\
left: calc((${j} * 100)/${gameSize[1]})%
}\
100% {\
top: calc((${i} * 100)/${gameSize[0]})%\
left: calc((${j} * 100)/${gameSize[1]})%\
}\
}\
\
`
style.innerHTML += keyframe;
newDiv.style.width = div.offsetWidth +'px';
newDiv.style.height = div.offsetHeight+'px';
newDiv.style.animationName = `animation-${i}-${j}`;
newDiv.style.animationDuration = '2s';
newDiv.style.position = 'absolute';
newDiv.style.animationFillMode = 'forwards';
newDiv.style.zIndex = 200;
var board = document.querySelector('.board');
board.appendChild(newDiv);
return checkWinner(map, gameSize[0], gameSize[1]);
}
每个单元格都有一个特殊的类,在我的实现中,我想要创建一个新元素(div),并使用z-index
而不是为选定的单元格设置动画。它已成功添加到DOM中,但我不知道为什么它无法正常工作!