2013-03-01 138 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/