如何逐像素移动DIV



我有一个这样的div设置。

  <div id="parent" class="parent">
            <div id="child" class="child">
            </div>
   </div>

风格
    <style>
    .parent{
    float:left; height:300; width:300px; background-color:#00ff00;
    }
    .child{
    float:left; height:60; width:60px; background-color:#00ff00;
    }
    </style>

<script>
            function move(){
                while(m < 100){
                document.getElementByid('child').style.marginTop = m;
                m = m+1;
                }
            }
            move();
 </script>

我想移动内部DIV(命名为child)逐像素从上到下移动100像素。我认为这可以用风格来完成。和settimeout()函数

下面是如何使用JavaScript为div添加动画:http://jsfiddle.net/z6F7m/1/

JavaScript

var elem = document.getElementById('animated'),
    top = parseInt(elem.style.marginTop, 10) || 0,
    step = 1;
function animate() {
    if (top < 100) {
        requestAnimationFrame(animate);
        elem.style.marginTop = top + 'px';
        top += step;
    }
}
animate();

我强烈建议您使用requestAnimationFrame而不是setTimeout,如果浏览器不支持requestAnimationFrame,您可以退回到setTimeout

试试这个

var element = document.getElementById('child');
for (var i=0; i != 100; i++){
    element.style.marginTop += 1;
}

这将循环100次,并在每次循环中为marginTop添加1。

我建议使用jQuery,因为使用jQuery你可以简单地做

$("#child").animate({ marginTop: 100 });

编辑

上面的例子没有意义,试试这个。

var element = document.getElementById('animated');
    for (var i = 0; i != 100; i++) {
    currentTop = parseInt(element.style.marginTop) || 0;
    newTop = parseInt(currentTop + 1);
    element.style.marginTop = newTop + "px";
}

这也是愚蠢的,因为它循环得太快了,当浏览器渲染框的时候,它已经离顶部100px了。看到

一种方法是使用jQuery的animate函数,这只需要编写:

$(element).animate({ 'top': '100px' });
示例

检查以下内容。我没有使用jquery。

 var step = 0;
 window.setInterval(function(){
    var value = (++step)*100;
    if (value<300)
        document.getElementById("child").style.marginTop=value+"px";
    else
       step = -1;
 },1000);
http://jsfiddle.net/pasindur/EbHt5/