所以我有这个动画,在当前状态下单击按钮时开始,但它没有停止,我的意图是使用javascript分配一个按钮,这将启动动画并在再次单击时删除动画属性(不暂停动画!)按钮应该在动画运行时将其名称更改为“停止”。很想得到解释的答案,因为刚开始使用javascript。提前致谢! :)
的CSS:
#kirby {
position: relative;
width: 20%;
/*animation-name: move;
animation-duration: 5s;
animation-timing-function: linear;
animation-iteration-count: infinite;*/
}
@keyframes move {
0% {
left: 0%;
}
49.99999% {
left: 65%;
}
50%{
left: -65%;
}
100%{
left: 0%;
}
};
使用Javascript:
var kirby = document.querySelector("#kirby");
var button1 = document.querySelector("#button1");
button1.addEventListener ("click", function (){
kirby.style.animation = "move 5s linear infinite";
});
答案 0 :(得分:2)
您可以将动画状态存储在变量中,然后在每次单击button
时检查状态并相应地执行操作,例如
var kirby = document.querySelector("#kirby");
var button1 = document.querySelector("#button1");
var playing = false;
button1.addEventListener ("click", function (){
if ( !playing ) { // If not playing
kirby.style.animation = "move 5s linear infinite";
// `this` refers to `button1`
// `innerText` refers to text content in `button1`
this.innerText = 'Stop'; // `this refers to `button1`
playing = true;
} else {
kirby.style.animation = ""; // clear the animation property
// `this` refers to `button1`
// `innerText` refers to text content in `button1`
this.innerText = 'Play';
playing = false;
}
});

#kirby {
position: relative;
width: 20%;
/*animation-name: move;
animation-duration: 5s;
animation-timing-function: linear;
animation-iteration-count: infinite;*/
}
@keyframes move {
0% {
left: 0%;
}
49.99999% {
left: 65%;
}
50%{
left: -65%;
}
100%{
left: 0%;
}
};

<div id="kirby">kirby</div>
<button id="button1">Start</button>
&#13;
答案 1 :(得分:0)
一种方法是在单击时将变量赋值为true,在未单击时将其赋值为false在if / else条件下使用此变量来启动和停止动画
答案 2 :(得分:-1)
您可以为按钮指定自定义属性,例如data-status
,如下所示:
<button data-status="on">Start</button>
现在,在您的事件回调中,您将检查该属性并切换其值。像这样:
var button = document.getElementById('button1');
button.addEventListener('click', function (ev) {
var status = ev.target.getAttribute('data-status');
if (status === 'on') {
//Stop
}
else if (status === 'off') {
//Start
}
});