【发布时间】:2017-09-29 07:37:29
【问题描述】:
我希望我的自定义元素在单击按钮时向右移动 200 像素。所以元素在点击时开始移动。在动画中我希望能够再次单击按钮停止并让元素动画返回初始状态(从当前状态反转动画)。
我通过 css 转换完成了这个:
var state = false;
var button = document.getElementById("but");
button.onclick = clickA;
function clickA(){
state = !state;
var el = document.getElementById("el");
if (state) el.setAttribute("class", "animatedElement open");
else el.setAttribute("class", "animatedElement");
}
.animatedElement {
padding-left: 0px;
transition: padding-left 5s;
}
.open {
padding-left: 200px;
}
<button id="but">Click</button>
<div id="el">element</div>
所以点击时我只需切换组件上的.open 类。
我想知道这是否可能与 css 动画有关?我试过这个:
var state = false;
var button = document.getElementById("but");
button.onclick = clickA;
function clickA(){
state = !state;
var el = document.getElementById("el");
if (state) el.setAttribute("class", "animatedComponent-open");
else el.setAttribute("class", "animatedComponent-close");
}
@keyframes animationOpen {
0% {padding-left: 0px;}
100% {padding-left: 200px;}
}
.animatedComponent-open {
animation: animationOpen 3s normal forwards;
}
@keyframes animationClose {
0% {padding-left: 0px;}
100% {padding-left: 200px;}
}
.animatedComponent-close {
animation: animationClose 3s reverse forwards;
}
<button id="but">Click</button>
<div id="el">element</div>
但这不会在动画中间点击时恢复打开的动画,而是跳转到最终状态,然后从头开始播放关闭动画。
【问题讨论】:
标签: javascript css css-animations frontend keyframe