是否可以在删除一个修改CSS属性的类后保留该属性(包括变量)?
问题出在下面的代码中,我想在删除类后保留青色方框的变换属性。animation-slide-to-left
这是因为当移除这个盒子时,它可以向左滑动。animation-slide-to-left
并添加类 animation-slide-to-right
类,我希望新的动画从旧的动画结束的地方开始。
但问题是当删除 animation-slide-to-left
变换属性会重置,并变为等于其在添加该类之前的旧值。
注意:我不想硬性地编写这个 transform
属性为0%,因为有很多动画,我正在寻找一种不用JAVASCRIPT就能自动解决问题的方法。
(将代码段结果展开到整页也可以看到这个例子)
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>
你可以在CSS关键帧中设置每次点击left和right按钮的起始位置,这样当按钮在左侧,点击right按钮时,首先将位置设置为左侧(0%),然后再向右做动画(100%),反之亦然。这样在点击按钮时就不会重置回中心了。
const box = document.querySelector (".animated");
function leftclicked (){
box.style.transform = 'translate(50%, -50%)';
box.classList.remove ("animation-slide-to-right");
box.classList.add ("animation-slide-to-left");
}
function rightclicked (){
box.style.transform = 'translate(-150%, -50%)';
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>
事实证明,没有JavaScript就没有必要创建这样的行为。因为如果一个CSS类在运行时被替换,我们已经在使用JavaScript了,所以解决方案是在删除旧类后,添加新类之前,在JavaScript中设置transform属性。