使用jquery进行div移动

时间:2014-10-22 17:36:53

标签: javascript jquery html settimeout

我尝试使用以下jquery代码每隔500毫秒从左到右进行50px的div移动:

<div id="obj"></div>
<script>
function move(before){
var howmuch = before + 50;
$("#obj").css("margin-left",howmuch + "px");
setTimeout(move(howmuch),500);
}
setTimeout(move(0),500);
</script>

#obj{
background-color:red;
width:100px;
height:100px;
border-radius:10px 10px 10px 10px;
-moz-border-radius:10px 10px 10px 10px;
-webkit-border-radius:10px 10px 10px 10px;
margin-left:0px;
}

...

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="obj"></div>
<script>
function move(before){
var howmuch = before + 50;
$("#obj").css("margin-left",howmuch + "px");
setTimeout(move(howmuch),500);
}
setTimeout(move(0),500);
</script>
</body>

但那不起作用。 当我使用Firefox或Internet Explorer启动时,框会立即离边距很远(比屏幕宽度大得多),现在我注意到如果我使用stackoverflow的代码片段功能运行它盒子不动。 可能是什么问题?

2 个答案:

答案 0 :(得分:3)

你的代码有一些错误,正确的方法是:

var howmuch = 0; // start at position 0, here its a global variable

function move(before) {
  howmuch = before + 50; // add 50 to the previous value
  $("#obj").css("margin-left", howmuch + "px"); // move it
  setTimeout(function() { //call next move, executing move function with current position after 500ms
    move(howmuch)
  }, 500);
}

setTimeout(function() { //start recursive funcion after 500ms, with 0 as start
  move(howmuch)
}, 500);

#obj {
  background-color: red;
  width: 100px;
  height: 100px;
  border-radius: 10px 10px 10px 10px;
  -moz-border-radius: 10px 10px 10px 10px;
  -webkit-border-radius: 10px 10px 10px 10px;
  margin-left: 0px;
}
<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <title>Test</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <div id="obj"></div>
  <script>
    var howmuch = 0;

    function move(before) {
      howmuch = before + 50;
      $("#obj").css("margin-left", howmuch + "px");
      setTimeout(function() {
        move(howmuch)
      }, 500);
    }
    setTimeout(function() {
      move(howmuch)
    }, 500);
  </script>
</body>

答案 1 :(得分:1)

以下是使用setInterval执行此操作的示例,因为setTimeout仅运行一次。

http://jsfiddle.net/7b4ybrux/1/

但你绝对应该看看dfionov所说的动画。