javascript - 使用css在某一类元素下方添加图像

标签 javascript css

我想做什么:

当元素的类更改为 activeCell 时,我想在元素 添加一个“walkingMan”图像。当使用伪类将图像添加到元素的前面或后面时,我知道该怎么做,但据我所知,没有像 :below 这样的东西可以用来达到同样的效果。我可以用 css 来模拟这个吗?

我做了什么:

我在每个上部单元格下方添加了图像,并在类更改为 activeCell 时使其可见。但我希望找到更简单的解决方案。

它的样子: enter image description here

代码:Simplified Code Example

最佳答案

您可以在 .cell 元素上使用单个伪元素,并在它处于事件状态时在其上放置背景图像。

let activeIndex = 0;
const cells = [...document.querySelectorAll('.cell')];
setInterval(() => {
  cells.forEach(cell => {
    cell.classList.remove('activeCell')
  });
  cells[activeIndex].classList.add('activeCell');
  activeIndex = activeIndex === cells.length - 1 ? 0 : (activeIndex + 1);
}, 300)
.cell {
  display: inline-block;
  border: 1px solid black;
  margin-bottom: 1.2em;
}

.activeCell {
  background-color: lightgrey;
  position: relative;
}

.activeCell::after {
  content: "";
  position: absolute;
  width: 1em;
  height: 1em;
  top: 1.3em;
  left: calc(50% - .5em); /* Center the stickman. Position it half of its width before the parent center*/
  background-image: url('https://www.shareicon.net/data/512x512/2016/01/17/704754_people_512x512.png');
  background-size:cover; /* Scale the stickman to completely cover the background area.  */
}
<div>
<div class='top'>
  <a class='cell'>One</a>
  <a class='cell'>One</a>
  <a class='cell'>One</a>
  <a class='cell'>One</a>
</div>
<div class='bottom'>
  <a class='cell'>One</a>
  <a class='cell'>One</a>
  <a class='cell'>One</a>
  <a class='cell'>One</a>
</div>
</div>

关于javascript - 使用css在某一类元素下方添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257873/

相关文章:

javascript - 如何使用 jquery 在 Bootstrap 5 中创建和修改弹出窗口?

html - 根据谷歌脚本中的图像大小调整行大小

Wordpress 菜单类上的 CSS 格式

javascript - WebSockets、Comet、AJAX 和长轮询

javascript - 为什么 Rx.Observable.throw(x) 实际上没有抛出?

Javascript从Weather Underground "history"API获取数据

HTML/CSS 如何水平对齐这些元素?

html - Bootstrap 下拉菜单溢出 html 正文

html - 在CSS3中创建图像上方的透明箭头

javascript - 分割的 cookie 字符串不起作用