2013-03-01 52 views
2

我有这样的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> 

我想通过像素从顶部100个像素移动内部DIV(名为子)像素底部。 我认为它可以使用style.marginTop =“”和的setTimeout()函数

但依然没能得到这个工作完成。

+9

向我们展示你的JavaScript代码。 – Halcyon 2013-03-01 16:40:25

+0

你是指动画吗? – Dogoku 2013-03-01 16:40:30

+0

@dogoku是动画。 – 2013-03-01 16:41:27

回答

5

这里是你如何动画与香草的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(); 

我强烈建议你使用​​代替setTimeout,如果浏览器不支持​​你可以回退到setTimeout。这样做的

+2

保罗爱尔兰垫片可能也值得包括:http://paulirish.com/2011/requestanimationframe-for-smart-animating/ – thesonglessbird 2013-03-01 16:46:36

2

试试这个

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

那将循环100次,加1到marginTop每个循环。

我建议使用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像素从顶部。 See here

再次,请使用jQuery solution

+0

如果'marginTop'是''10px'',这不会使它成为'10px11111 ...',我们还会有动画吗? – 2013-03-01 16:48:46

+0

好点,更新! – dotty 2013-03-01 17:01:15

1

一种方法是使用jQuery的animate功能,这将需要仅仅写着:

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

Example

+0

顶部将只在绝对位置时才有效。利润率最高的是这种情况。 – dotty 2013-03-01 17:01:56

+0

它也适用于职位:相对 - 正如你最可能意识到的那样。不知道使用情况的真实例子,争论哪种方法最适合没有意义。 – 2013-03-01 17:05:57

0

检查以下小提琴。我做了没有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/