【发布时间】:2020-06-12 18:45:48
【问题描述】:
是否可以在删除修改它们的类后保留 CSS 属性(包括变量)?
问题出在下面的代码中。
在删除将框向左滑动的类animation-slide-to-left 之后,我想保留青色框的变换属性。
那是因为当删除 animation-slide-to-left 并添加类 animation-slide-to-right 类时,我希望新动画从旧动画结束的地方开始。
但问题是当删除animation-slide-to-left 时,变换属性会重置并等于添加该类之前的旧值。
注意:我不想将transform 属性硬编码为 0%,因为有很多动画,我正在寻找一种无需 JAVASCRIPT 自动解决问题的方法。
(将 sn-p 结果扩展到整页也请参见示例)
const box = document.querySelector (".animated");
function leftclicked (){
box.classList.remove ("animation-slide-to-right");
box.classList.add ("animation-slide-to-left");
}
function rightclicked (){
box.classList.remove ("animation-slide-to-left");
box.classList.add ("animation-slide-to-right");
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.animated {
animation-duration: 0.5s;
animation-delay: 0s;
animation-iteration-count: 1;
animation-direction: normal;
animation-timing-function: ease-out;
animation-fill-mode: forwards;
}
.animation-slide-to-left {
animation-name: slide-to-left;
}
.animation-slide-to-right {
animation-name: slide-to-right;
}
@keyframes slide-to-left {
100%{
transform: translate(-150%, -50%);
}
}
@keyframes slide-to-right {
100%{
transform: translate(50%, -50%);
}
}
<div class="center" style="width:300px; height: 300px; background-color: red;">
<div class="center animated" style="width: 50%; height: 50%; background-color:cyan;">
</div>
<button style="float:left;" onclick="leftclicked()">LEFT</button>
<button style="float:right;" onclick="rightclicked()">RIGHT</button>
</div>
【问题讨论】:
标签: html css web css-animations css-transforms