Передача параметров в css-анимацию
p {
animation-duration: 3s;
animation-name: slidein;
}
@keyframes slidein {
from {
margin-left: 100%;
width: 300%;
}
to {
margin-left: 0%;
width: 100%;
}
}
Для приведенного выше кода CSS анимации, мне интересно, есть ли способ передать значения margin-left и width в качестве параметра из Javascript.
Свободный перевод вопроса Passing parameters to css animation от участника @Qian Chen.
Ответы (2 шт):
Автор решения: Alexandr_TT
→ Ссылка
Используйте переменные CSS, и вы легко можете это сделать:
document.querySelector('.p2').style.setProperty('--m','100%');
document.querySelector('.p2').style.setProperty('--w','300%');
.p1,.p2 {
animation-duration: 3s;
animation-name: slidein;
}
@keyframes slidein {
from {
margin-left: var(--m, 0%);
width: var(--w, 100%);
}
to {
margin-left: 0%;
width: 100%;
}
}
<p class="p1">
This will not animate as the animation will use the default value set to the variable
</p>
<p class="p2">
This will animate because we changed the CSS variable using JS
</p>
Свободный перевод ответа от участника @Temani Afif.
Автор решения: DiD
→ Ссылка
Или например вот так:
document.styleSheets[0].cssRules[1][1].style.background='red'
.blue {
width: 30px;
height: 30px;
margin: 30px;
background: blue;
float: left;
animation: animation 1s infinite;
}
@keyframes animation {
from {
transform: translate(0, 0);
background: blue;
}
to {
transform: translate(300px, 0);
background: green;
}
}
<div class="blue"></div>
<div class="blue"></div>
<div class="blue"></div>