如何循环这个javascript对象?

时间:2015-09-25 17:09:07

标签: javascript html

我有这个代码,只是简单的代码,但基本上我希望它自动返回到右边并再次循环(从右到左,再次在左侧显示的窗口右侧)现在这个代码只使对象从左向右无限移动 有可能吗?

var imgObj = null;
var animate;

function init() {
  imgObj = document.getElementById('myImage');
  imgObj.style.position = 'relative';
  imgObj.style.left = '0px';
}

function moveRight() {
  imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
  animate = setTimeout(moveRight, 20); // call moveRight in 20msec
}

function stop() {
  clearTimeout(animate);
  imgObj.style.left = '0px';
}

window.onload = init;
<html>
<head>
  <title>JavaScript Animation</title>
</head>

<body>
  <form>
    <img id="myImage" src="/images/html.gif" />
    <p>Click the buttons below to handle animation</p>
    <input type="button" value="Start" onclick="moveRight();" />
    <input type="button" value="Stop" onclick="stop();" />
  </form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

当您的图像超过窗口宽度时,需要将其位置重置为零。您可以使用模数运算符执行此操作。

var imgObj = null;
var animate;

function init() {
  imgObj = document.getElementById('myImage');
  imgObj.style.position = 'relative';
  imgObj.style.left = '0px';
}

function moveRight() {
  var bodyWidth = document.body.clientWidth;
  var newLeft = parseInt(imgObj.style.left) + 10
  imgObj.style.left = newLeft % bodyWidth + 'px';
  animate = setTimeout(moveRight, 20); // call moveRight in 20msec
}

function stop() {
  clearTimeout(animate);
  imgObj.style.left = '0px';
}

window.onload = init;
<html>

<head>
  <title>JavaScript Animation</title>



</head>

<body>

  <form>
    <img id="myImage" src="/images/html.gif" />
    <p>Click the buttons below to handle animation</p>
    <input type="button" value="Start" onclick="moveRight();" />
    <input type="button" value="Stop" onclick="stop();" />
  </form>

</body>

</html>