使用JavaScript“动画”我的网页

时间:2009-12-02 13:30:21

标签: 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>

1 个答案:

答案 0 :(得分:2)

使用像jQuery这样的标准库来执行此操作,不要自己动手,因为它不会是跨浏览器肯定

使用jQuery,您可以执行以下操作:

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

这将在1000毫秒= 1秒内将div高度更改为300 px。