【问题标题】:Rotate only the ::after content, not the whole element仅旋转 ::after 内容,而不是整个元素
【发布时间】:2021-07-15 17:44:47
【问题描述】:

我有以下 CSS 类,它表示网格中的 Tile

.col {
  background: #ffffff;
  user-select: none;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 25px;
  min-width: 25px;
  height: 100%;
  border-right: 1px solid #afd8f8;
  border-bottom: 1px solid #afd8f8;
}

我稍后用 JavaScript 将以下 CSS 类添加到 Tile,这个 CSS 类代表一个 Player

.player {
  position: relative;
  &::after {
    z-index: 99;
    content: "";
    width: 18px;
    height: 18px;
    position: relative;
    background: url(./../assets/player.svg);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
  }
}

这是 player.svg:

包含播放器的 Tile div 最终看起来像这样:

<div class="col player">< /div>

我想为播放器设置动画,以便在他上升时旋转 -90 度

我正在尝试使用 JavaScript 添加此功能,但似乎我正在旋转整个 div(弄乱了我的一些游戏逻辑)。我期待只旋转 播放器 而不是整个 div。

我尝试了以下方法:

grid[i][j].DOMElement.style.transform = 'rotate(-90deg)';

grid[i][j].DOMElement 返回特定的 HTMLElement 平铺

但正如我之前所说,这会旋转整个 div...

任何帮助将不胜感激。提前致谢!

【问题讨论】:

标签: javascript html css sass


【解决方案1】:

向父级添加一个类并使用它来修改::after 可能最简单

.player {
  position: relative;
  &::after {
    z-index: 99;
    position: absolute;
    content: "";
    width: 18px;
    height: 18px;
    position: relative;
    background: url(./../assets/player.svg);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
  }
  &.rotated::after {
    transform: rotate(-90deg)
  }
}

grid[i][j].DOMElement.classList.add("rotated")

【讨论】: