使用javascript移动css元素的代码有什么问题?

时间:2013-12-10 12:13:42

标签: javascript css

我正在尝试使用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>   

1 个答案:

答案 0 :(得分: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