2016-06-15 85 views
0

我認爲這是工作,但不是真的。我也不認爲這是最好的方法。如何脈衝圖像並改變脈衝率?

定時器作爲另一個功能運行,同時有能力改變圖像的脈衝速率。

我試圖使用gif而不是因爲它們具有不同的速度,在圖像之間切換時沒有平滑過渡。

<!DOCTYPE HTML> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script> 
     <style> 
      #red-square { 
       position: absolute; 
       display: inline-block; 
       z-index: 1; 
       top : 200px; 
       right: 200px; 
       height: 100px; 
       width: 100px; 
       background-color: red; 
      } 
     </style> 
    </head> 
    <body> 
     <div id="result"></div> 
     <div id="red-square"></div> 
     <button onclick="speedOne();">speed one</button> 
     <button onclick="speedTwo();">speed two</button> 
     <button onclick="speedThree();">speed three</button> 
     <script> 

    var counter   = 0, 
     stopTimeoutTwo = null, 
     stopTimeoutThree = null, 
     currentSpeed  = "speed one"; 

    function runCounter() { 
     counter++; 
     result.textContent = counter; 
     if(currentSpeed == "speed one") { 
      if((counter%60) == 0) { 
       $("#red-square").hide(); 
      }else if((counter%60) != 0) { 
       $("#red-square").show(); 
      } 
     } 
     else if(currentSpeed = "speed two") { 
      if((counter%45) == 0) { 
       $("#red-square").hide(); 
      }else if((counter % 45) != 0) { 
       $("#red-square").show(); 
      } 
     }else if(currentSpeed = "speed three") { 
      if((counter%30) == 0) { 
       $("#red-square").hide(); 
      }else if((counter%30) != 0) { 
       $("#red-square").show(); 
      } 
     } 
     if(counter < 1e5) timer = setTimeout(runCounter, 0); 
    } 

    runCounter(); 

    function stepOne() { 
     currentSpeed = "speed one"; 
    } 
    function stepTwo() { 
     currentSpeed = "speed two"; 
    } 
    function stepThree() { 
     currentSpeed = "speed three"; 
    } 

    </script> 
    </body> 
</html> 
+0

使用__ [setInterval](http://www.w3schools.com/jsref/met_win_setinterval.asp)__當點擊速度,改變間隔... –

回答

1

您可以用setInterval來創建效應,像這樣: Fiddle!

這是我用JS:

var speed = 4000; 
var inter; 
var square = document.getElementById("red-square"); 
square.style.backgroundColor = "red"; 
function myTime(){ 
    inter = setInterval(function(){ 
      console.log(square.style.backgroundColor+" "+speed); 
     if(square.style.backgroundColor == "red"){ 
     square.style.backgroundColor = "blue"; 
     } 
     else{ 
     square.style.backgroundColor = "red"; 
     } 
    }, speed); 
} 

function changSpeed(s){ 
    clearInterval(inter); 
    speed = s; 
    inter=null; 
    myTime(); 
} 
myTime(); 

剩下的就是你的代碼。

+0

這很好,謝謝,我會試試出來。 – joehungjohn