我有一个由 nxn 个较小的方形 div 元素组成的方形网格,我想用 CSS 背景颜色动画按顺序照亮这些元素。我有一个函数来为序列生成一个随机数组。我遇到的问题是,一旦某个方块被照亮一次,如果它再次出现在阵列中,它就不会第二次照亮。我相信这是因为一旦为元素分配了 CSS 动画,动画就无法在该元素上再次触发,而且我无法找到使其工作的方法。这是我正在学习的响应式 Web 应用程序课程,评估规定我们只能使用 vanilla JS,并且所有元素必须在 JS 中创建并附加到<body>我们的 index.html 中的空白处。
根据序列的每个闪光都是通过 setTimeout 函数触发的,该函数循环遍历数组中的所有元素,每次循环将其计时器增加 1 秒(动画长度也是 1 秒)。
定义容器和子 div:
function createGameContainer(n, width, height) {
var container = document.createElement('div');
//CSS styling
container.style.margin = '50px auto'
container.style.width = width;
container.style.height = height;
container.style.display = 'grid';
// loop generates string to create necessary number of grid columns based on the width of the grid of squares
var columns = '';
for (i = 0; i < n; i++) {
columns += ' calc(' + container.style.width + '/' + n.toString() + ')'
}
container.style.gridTemplateColumns = columns;
container.style.gridRow = 'auto auto';
// gap variable to reduce column and row gap for larger grid sizes
// if n is ever set to less than 2, gap is hardcoded to 20 to avoid taking square root of 0 or a negative value
var gap;
if (n > 1) {
gap = 20/Math.sqrt(n-1);
} else {
gap = 20;
}
container.style.gridColumnGap = gap.toString() + 'px';
container.style.gridRowGap = gap.toString() + 'px';
container.setAttribute('id', 'game-container');
document.body.appendChild(container);
}
/*
function to create individual squares to be appended to parent game container
*/
function createSquare(id) {
var square = document.createElement('div');
//CSS styling
square.style.backgroundColor = '#333';
//square.style.padding = '20px';
square.style.borderRadius = '5px';
square.style.display = 'flex';
square.style.alignItems = 'center';
//set class and square id
square.setAttribute('class', 'square');
square.setAttribute('id', id);
return square;
}
沧海一幻觉
温温酱
相关分类