2014-01-31 25 views
0

我想將2個事件處理程序附加到一個button以分別啓動和停止動畫。我正在嘗試使用boolean值來測試動畫是否已在運行,因此觸發了正確的事件處理程序。即如果動畫未運行,則boolean爲假,因此運行動畫事件處理程序將觸發。只要我嘗試添加這些處理程序中的任何一個或兩個,代碼就會中斷並且動畫將無法運行。我之前沒有嘗試在元素上使用2個事件處理程序,並且在線看到的內容很少,所以我不確定是否以正確的方式進行操作。將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); 
} 

回答

0

你看這個:

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); 
} 
相關問題