У меня есть один элемент div с псевдо-элементом ::before, который имеет z-index: -1, чтобы его можно было поместить за фактическим элементом 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-индексом и позволит избежать необходимости использовать другую анимацию, чтобы вернуть ту, которая была применена к основному элементу.
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>
Спасибо @Temani Afif. Не знаю, почему я не подумал использовать
::beforeи::afterдля шара и тени.