繁体   English   中英

基本的Javascript动画

[英]Basic Javascript Animation

这里是非常基本的动画练习:

的HTML

<div id="div"></div>

JS

div = document.getElementById("div")

div.onmouseover = move();

function move() {
    cHeight = div.style.height;

    while (cHeight < 300) {
        div.style.height = (cHeight + 10) + "px";
        setTimeout (move, 20);
    }
}

当我加载页面(它仍然是本地文件)时,它无法加载,并且我得到了Chrome的“ aw snap,页面无法加载”错误页面。 这很奇怪,因为正如我所说,它仍然是本地的。 救命?

实际上,您根本不应该使用while循环。

function move() {
  var cHeight = div.style.height;

  if ( cHeight < 300 ) {
    div.style.height = (cHeight + 10) + "px";
    setTimeout(move, 20); //This way the height only changes every 20ms
  }
}

在您的代码中,您永远不会增加cHeight >无限循环

如果仅您自己设置,style.height属性将被设置。 而是尝试div.clientHeight或div.offsetHeight。 OffsetHeight相同,但包括填充,边框和边距。

您的代码中还有其他问题。 您正在立即调用move函数,而不仅仅是将其分配为处理函数,并且您的动画代码本身有点破损-您不需要while循环和超时。

我编写了一个片段,该片段可能与您想要的内容相似:

 <div id="div" style="width: 50px; height: 50px; background: red;"> </div> <script type="text/javascript"> var div = document.getElementById("div") div.onmouseover = move; function move() { if(div.offsetHeight < 300) { div.style.height = (div.offsetHeight + 10) + "px"; setTimeout(move, 20); } } </script> 

您陷入了无限循环! 发生这种情况是因为您从不更新cHeight,并且将递归与迭代结合在一起。

function move() {

    var cHeightStr = div.style.height.substr(-2);
    var cHeight = cHeightStr.substr(0, cHeightStr.length - 2);

    if (cHeight < 300) {
        cHeight += 10;
        div.style.height = cHeight + "px";
        setTimeout (move, 20);
    }
}

好的,这里发生了一些坏事,您不希望使用while循环,因为它会在所有位置之前移动,从而使浏览器有机会呈现任何更改,并且它实际上不会退出循环...

此页面上的其他示例也使用div.style.height,该字符串以空白字符串开头。 主要是通过JS覆盖文档样式的说明。 因此,它将仅返回您先前在JS中设置的值,而不返回div的实际位置。

function move() {
    var cHeight = div.offsetTop; //this returns the current calculated top offset from the container

    if(cHeight < 300) { // if we're under 300 then update position
        div.style.height = (cHeight + 10) + "px";
        setTimeout (move, 20); //wait for next frame then update position again
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM