2014-01-31 5 views
0

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); 
} 

답변

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); 
} 
관련 문제