我想将2个事件处理程序附加到一个button
,分别开始和停止动画。我尝试使用boolean
值来测试动画是否已经运行,以便触发正确的事件处理程序。即,如果动画没有运行,则boolean
为假,因此运行动画事件处理程序将被触发。只要我尝试添加这两个处理程序中的一个或两个,代码就会中断,动画就不会运行。我以前没有尝试过在一个元素上使用2个事件处理程序,也很少在网上看到它,所以我不确定我这样做的方式是否正确。
如何附加这些处理程序来启动和停止动画?
<div id='robotCont'></div>
<button id='animeBtn'>start/stop animation</button>
div#robotCont {
width:125px;
height:160px;
border:1px solid #22e;
background-image:url("images/robot.jpg");
background-repeat: no-repeat;
background-position: 0px 0px;
}
var robotSwitch = false;
document.getElementById('animeBtn').onclick = function() {
if(robotSwitch == false) {
runningRobot();
} else {
stopRobot();
}
}
var decrement = 0;
function runningRobot() {
var robotCont = document.getElementById('robotCont');
if(decrement < -1900) {
decrement = 0;
}
robotCont.style.backgroundPosition = decrement+ 'px 0px';
decrement -= 120;
timer = setTimeout(runningRobot,100);
robotSwitch = true;
}
function stopRobot() {
clearTimeout(timer);
}
发布于 2014-01-31 18:24:54
这样如何:
var animate = false
timer;
document.getElementById('animeBtn').onclick = function() {
animate = !animate;
if(animate) {
runningRobot();
} else {
stopRobot();
}
}
var decrement = 0;
function runningRobot() {
var robotCont = document.getElementById('robotCont');
if(decrement < -1900) {
decrement = 0;
}
robotCont.style.backgroundPosition = decrement+ 'px 0px';
decrement -= 120;
timer = setTimeout(runningRobot,100);
}
function stopRobot() {
clearTimeout(timer);
}
https://stackoverflow.com/questions/21477485
复制相似问题