我想做什么:
当元素的类更改为 activeCell
时,我想在元素下 添加一个“walkingMan”图像。当使用伪类将图像添加到元素的前面或后面时,我知道该怎么做,但据我所知,没有像 :below
这样的东西可以用来达到同样的效果。我可以用 css 来模拟这个吗?
我做了什么:
我在每个上部单元格下方添加了图像,并在类更改为 activeCell
时使其可见。但我希望找到更简单的解决方案。
最佳答案
您可以在 .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/