如何逐像素移动DIV

3

我有一个如下所示的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个像素。我认为可以使用style.marginTop =''和settimeout()函数来实现。

但仍然不能使其正常工作。


9
请展示您的 JavaScript 代码。 - Halcyon
@dogoku 是的,正在进行动画制作。 - Ravish Kumar
如果你想要一些动画效果,可以尝试使用jQuery。 - Mihai8
2
如果浏览器支持不是一个问题,您也可以使用CSS过渡效果。 - thesonglessbird
我在想是否有人会提到过渡或动画。 - Dogoku
显示剩余2条评论
4个回答

7

以下是如何使用原生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


2
Paul Irish的shim也许值得包含:http://paulirish.com/2011/requestanimationframe-for-smart-animating/ - thesonglessbird

2

试试这个

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";
}

这样做很愚蠢,因为它循环得太快了,在浏览器渲染出框之前,它已经距顶部100像素了。可以在这里看到

建议使用jQuery 解决方案


如果 marginTop'10px',那么它不会变成 10px11111... 吗?这样会有动画效果吗? - Minko Gechev

1

一种方法是使用jQuery的animate函数,只需编写以下代码:

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

{{链接1:示例}}


Top 只有在其位置为绝对定位时才有效。margin-top 是这种情况下最好的选择。 - dotty
它也适用于position: relative - 正如您可能已经意识到的那样。不知道实际使用示例,争论哪种方法最合适是没有意义的。 - Maciej Gurban

0
检查下面的fiddle。我没有使用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/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接