2009-12-02 28 views
0

我想我會寫一個簡單的腳本來爲我的網頁製作一點點動畫。使用JavaScript來「動畫」我的網頁

最基本的想法是讓一個div變大一點,當我按下按鈕一次,然後縮小到原來的大小,再次按下它。我處理的不斷增長的部分,但我不能讓它再次縮小。

我包括一個完整的例子,你能幫我修復嗎?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

    <head> 
     <title>Test</title> 
     <meta http-equiv="Content-Language" content="Estonian" /> 
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15" /> 
    </head> 

    <body> 
     <script type="text/javascript"> 
      var i; 
      var increasing = new Boolean("true"); 
      var height; 

      function testFunction() { 
       height = parseInt(document.getElementById("testDiv").offsetHeight); 
       if(increasing == true) { 
        i = height + 4; 
        document.getElementById("testDiv").style.height = i + "px"; 
        if(height >= 304) { 
         increasing = false; 
        } 
        else { 
         pause(30); 
        } 
       } 
       else { 
        i = height - 4; 
        document.getElementById("testDiv").style.height = i + "px"; 
        if(height <= 104) { 
         increasing = true; 
        } 
        else { 
         pause(30); 
        } 
       } 
      } 
      function pause(ms) { 
       setTimeout("testFunction()", ms); 
      } 
     </script> 
     <button id="button" type="button" onclick="testFunction();">Do it!</button. 
     <div id="testDiv" style="border: 2px solid black; width: 400px; height: 100px; text-align: center;"> 
      Hello! 
     </div> 
    </body> 

</html> 
+0

不要這樣做它是一切邪惡的根源! – JonH 2009-12-02 13:31:57

+1

也許你自己在做這個學習練習,但是你知道有像Scriptaulous這樣的圖書館可以做到嗎? – 2009-12-02 13:35:26

+0

這可能是一個錯字,但:「做到了!」' – 2009-12-02 14:01:01

回答

2

使用標準的庫如jQuery做到這一點,你自己不要這樣做,因爲它不會是跨瀏覽器肯定

使用jQuery,你可以做這樣的事情:

$("#div-id").animate({"height": 300}, 1000); 

這將在1000毫秒= 1秒的div高度更改爲300像素。

+1

謝謝,這似乎是最合理的解決方案。 – ehehhh 2009-12-02 13:52:32