2013-12-10 32 views
0

我想用javascript移動一個元素。我搜索了一段時間,我認爲這個代碼應該做的伎倆......但它不,我沒有在控制檯中的錯誤...任何人都可以幫助?這段代碼用javascript移動css元素有什麼問題?

<html><body> 
    <script> 
    function move1(){ 
    var cusid_ele = document.getElementsByClassName('zzz'); 
    for (var i = 0; i < cusid_ele.length; ++i) { 
     var item = cusid_ele[i]; 
     var x=item.style.top; 
     x+=10; 
     item.style.top=x; 
    } 
    } 
    function move2(){ 
    var cusid_ele = document.getElementsByClassName('zzz'); 
    for (var i = 0; i < cusid_ele.length; ++i) { 
     var item = cusid_ele[i]; 
     var x=item.style["top"]; 
     x+=10; 
     item.style["top"]=x; 
    } 
    } 
    function move3(){ 
    var cusid_ele = document.getElementsByClassName('zzz'); 
    for (var i = 0; i < cusid_ele.length; ++i) { 
     var item = cusid_ele[i]; 
     var x=item.style["top"]; 
     x+=10; 
     item.style["top"]=x+'px'; 
    } 
    } 
    </script> 
    <input type=button onclick="move1();" value="Move (1st way, with .top=x)!"> 
    <input type=button onclick="move2();" value="Move (2nd way, with [top]=x)!"> 
    <input type=button onclick="move3();" value="Move (3rd way, with [top]=xpx)!"> 
    <h3 class=zzz >Move me! (no inline style)</h3> 
    <h3 class=zzz style="top: 50px;">Move me! (with inline style)</h3> 
    </body></html> 

順便說一句,我都嘗試FF和鉻...

- 接受的解決方案,我在這裏寫這樣一個可以工作的例子(謝謝Adeneo!):

<script> 
function move1(){ 
    var cusid_ele = document.getElementsByClassName('zzz'); 
    for (var i = 0; i < cusid_ele.length; ++i) { 
     var item = cusid_ele[i]; 
     var x = parseInt(item.style.top, 10); 
     x+=10; 
     item.style.top=x+'px'; 
    } 
} 
</script> 
<input type=button onclick="move1();" value="Move!">      
<h3 class=zzz >I cant move! (no css positioning)</h3> 
<h3 class=zzz style="position: relative; top: 50px;">I can move! (with css positioning)</h3> 
</body></html> 
+0

u能分享ZZZ類?它是否包含絕對定位? –

+0

這裏沒有css,zzz類是「空」 – d3k

回答

4

var x=item.style["top"]; 

返回字符串300px等,所以

x += 10; 

最終被

300px10 

所以更換

var x=item.style.top; 

var x = parseInt(item.style.top, 10); 

也是如此設置樣式

element.style.top = x + 'px'; 

你必須使用帶單位的字符串,並且使CSS做一些實際的元素必須位於

FIDDLE

+0

它適合你嗎?對我而言,即使這樣,它也不起作用...(var i = 0; i d3k

+0

得到了「該元素必須定位」,現在它的工作!謝謝! – d3k