2016-06-15 54 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