【发布时间】:2017-01-06 04:57:15
【问题描述】:
我想做什么
我有一个精灵表,我将它用于一些简单的动画。我有一个有两个动画的“播放器”。一种用于攻击,一种用于站立。当前行为如下:“stand”是默认动画。当玩家被点击时,播放“攻击”动画并切换回“站立”。
对于玩家在攻击时被点击的特殊情况,我希望动画“攻击”动画重置。
我的代码
// React Component
class Player extends React.Component {
constructor(props) {
super(props);
this.state = {
timeout: null
};
}
attack(e) {
if (this.state.timeout) { clearTimeout(this.state.timeout); }
var $el = $(e.target);
$el.css({
backgroundPosition: '0 220px',
animationName: 'attack',
width: '300px'
});
this.state.timeout = setTimeout(function() {
$el.css({
backgroundPosition: 'left top',
animationName: 'stand',
width: '250px'
});
}, 2000);
}
render () {
return (
<div onClick={this.attack.bind(this)} className="player main">{this.props.name}</div>
);
}
}
/* The css */
.player {
width: 250px;
height: 220px;
background: url('assets/player.png') left top;
animation: stand 1.2s steps(3) infinite;
animation-direction: alternate;
}
@keyframes stand {
100% {
background-position: -750px 0;
}
}
@keyframes attack {
100% {
background-position: -900px 220px;
}
}
我想做什么
我知道,既然我设置了“站立”动画,我将不得不取消它并制作一个新的 setTimeout 来跟随“站立”动画。但是,它看起来仍然有点时髦。我尝试使用 forceUpdate() 来查看是否可以重新渲染并重置所有内容,然后启动“攻击”动画,但它似乎没有做任何事情。
我有另一个想法,使用 jquery 删除和重新附加 dom 元素,但我觉得它会变得混乱,我相信我可能以错误的方式处理这个问题。大家有什么想法吗?
【问题讨论】:
标签: javascript css animation reactjs