Make a div move using jquery

血红的双手。 提交于 2019-12-13 06:45:09

问题


I'm trying to make a div move of 50px from left to right every 500 milliseconds with the following jquery code:

<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>

But that's not working. When I launch it with Firefox or Internet Explorer, the box gets immediately to a huge distance from the margin (much bigger than the width of the screen), and now I noticed that if I run it with stackoverflow's snippet function the box does not move. What could be the problem?


回答1:


You code has a few mistakes, correct way is:

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>



回答2:


Here is an example of doing it with setInterval, because setTimeout is run only once.

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

But you definitely should look at animate as dfionov stated.



来源:https://stackoverflow.com/questions/26513621/make-a-div-move-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!