使用jQuery进行div移动 [英] Make a div move using jquery

查看:73
本文介绍了使用jQuery进行div移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下jquery代码每500毫秒从左向右移动50px的div:

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>

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

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?

推荐答案

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

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>

这篇关于使用jQuery进行div移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆