什么'这段用javascript移动css元素的代码错了

What's wrong with this code to move css elements with javascript?

本文关键字:元素 css 代码 错了 移动 javascript 段用 什么      更新时间:2024-06-09

我正在尝试用javascript移动一个元素。我搜索了一段时间,我认为这个代码应该起作用。。。但它没有,而且我在控制台中没有得到任何错误。。。有人能帮忙吗?

  <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和Chrome。。。

--接受的解决方案,我把它写在这里,这样人们就可以有一个工作的例子(谢谢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>   

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