多个元素上的 CSS 动画:悬停后重新同步

问题描述 投票:0回答:2

我正在制作一个游戏,你可以点击一个方块来显示一个字母。这些块具有“发光”效果,它们通过淡入白色并返回到原始颜色来改变颜色。此效果持续 2 秒并无限重复。

当您将鼠标悬停在其中一个方块上时,该方块会变成红色。我的问题是,当鼠标离开该块时,动画会从头开始,并且可能与其他块不同步。有没有想法让块动画同步,而不依赖于鼠标悬停?

最小可重现示例:

let grid = document.getElementById("grid");

for (i = 0; i < 4; i++){
  let row = document.createElement("div");
  row.className = "row";
  
  for (j = 0; j < 4; j++){
    let box = document.createElement("div");
    box.className = "box";
    box.classList.add("hoverable");
    row.appendChild(box);
  }
  grid.appendChild(row);
}
.box {
  /*background-color: blue;*/
  width: 50px;
  height: 50px;
  animation: fade 2s ease-in-out infinite;
  border: solid 1px black;
}

.hoverable:hover {
  background-color: red;
  animation: 0;
}

.row {
  display: flex;
  flex-direction: row;
}

@keyframes fade {
    0%   { background-color: blue; }
    50%  { background-color: #FFFFFF; }
    100% { background-color: blue; }
}
<div class="grid" id="grid"></div>

javascript html css css-animations
2个回答
0
投票

您可以简单地使用

background-color: red !important;
...

let grid = document.getElementById('grid');

for (i = 0; i < 4; i++) {
  let row = document.createElement('div');
  for (j = 0; j < 4; j++) {
    row.appendChild( document.createElement('div') );
  }
  grid.appendChild(row);
}
#grid > div {             /*  rows */
  display        : flex;
  flex-direction : row;
}

#grid > div > div {        /* boxs */
  width      : 50px;
  height     : 50px;
  animation  : fade 2s ease-in-out infinite;
  border     : solid 1px black;
  }

#grid > div > div:hover {
  background-color: red !important;
  }

@keyframes fade {
    0%   { background-color : blue; }
    50%  { background-color : white; }
    100% { background-color : blue; }
}
<div id="grid"></div>


0
投票

使用带有渐变的额外图层

let grid = document.getElementById("grid");

for (i = 0; i < 4; i++){
  let row = document.createElement("div");
  row.className = "row";
  
  for (j = 0; j < 4; j++){
    let box = document.createElement("div");
    box.className = "box";
    box.classList.add("hoverable");
    row.appendChild(box);
  }
  grid.appendChild(row);
}
.box {
  background-color: blue;
  width: 50px;
  height: 50px;
  animation: fade 2s ease-in-out infinite;
  border: solid 1px black;
  
}

.hoverable:hover {
  background-image: linear-gradient(red 0 0);
}

.row {
  display: flex;
  flex-direction: row;
}

@keyframes fade {
    50%  { background-color: #FFFFFF; }
}
<div class="grid" id="grid"></div>

© www.soinside.com 2019 - 2024. All rights reserved.