我有一个带有伪
::before
元素的 div,该元素具有 z-index: -1
以便放置在实际 div 后面。 div 是一个“球”,伪元素是它的阴影。
还有一个按钮,单击时会在 div 上放置动画,使其上下弹跳。问题在于,当启用动画时,阴影(伪 div)才会被放置在球(实际 div)的前面。
document.querySelector("button").addEventListener("click", () => {
document.body.classList.toggle("disable-animation");
})
*,
*::before,
*::after {
position: relative;
min-width: 0;
padding: 0;
margin: 0;
box-sizing: border-box;
}
*::before,
*::after {
content: '';
position: absolute;
}
body {
min-height: 100vh;
background-color: rgba(0,0,0,.2);
display: grid;
place-items: center;
}
div[ball] {
width: 10vw;
aspect-ratio: 1;
background-color: #fff;
border-radius: 50%;
--jump: 4vw;
animation: var(--animation);
animation-timing-function: ease-in-out;
}
div[ball]::before {
width: 100%;
height: 15%;
bottom: -.5vw;
background-color: rgba(0,0,0,.1);
border-radius: 50%;
z-index: -1;
--jump: -4vw;
animation: var(--animation);
animation-timing-function: ease-in-out;
}
@keyframes ball-jump {
50% {
transform: translate3d(0, calc(-1 * var(--jump)), 0);
}
}
.disable-animation {
--animation: ball-jump 1s infinite;
}
<div ball></div>
<button>Toggle animation</button>
我已在 Firefox 123、Google Chrome 122.0.6261.95 和 Microsoft Edge 121.0.2277.128 中尝试过此示例。因为 Firefox 和其他浏览器不共享渲染引擎,所以我认为这不是一个错误,而是我做错了什么。只是不知道什么?
使用两个伪元素来创建动画。这将解决 z-index 问题,并避免必须处理另一个动画来恢复应用于主元素的动画
document.querySelector("button").addEventListener("click", () => {
document.body.classList.toggle("disable-animation");
})
body {
margin: 0;
min-height: 100vh;
background-color: rgba(0,0,0,.2);
display: grid;
place-items: center;
}
div[ball] {
width: 10vw;
aspect-ratio: 1;
position: relative;
}
div[ball]::before {
content:"";
position: absolute;
width: 100%;
height: 15%;
bottom: -.5vw;
background-color: rgba(0,0,0,.1);
border-radius: 50%;
}
div[ball]::after {
content:"";
position: absolute;
inset: 0;
background-color: #fff;
border-radius: 50%;
--jump: 4vw;
animation: var(--animation);
animation-timing-function: ease-in-out;
}
@keyframes ball-jump {
50% {
transform: translate3d(0, calc(-1 * var(--jump)), 0);
}
}
.disable-animation {
--animation: ball-jump 1s infinite;
}
<div ball></div>
<button>Toggle animation</button>