基于style.right重置位置

Resetting position based on style.right

本文关键字:置位 位置 right style 基于      更新时间:2023-09-26

当图像到达屏幕的最右边时,我试图重置动画。

没有这条线,一切都很好:

if (imgObj.style.right == 0) {
    Reset();
}

这不是正确的方式吗?

<!--
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, 2000); // call moveRight in 20msec
  if (imgObj.style.right == 0) {
    Reset();
  }
}
function Reset() {
  clearTimeout(animate);
  imgObj.style.left = '0px';
}
window.onload = init;
//-->
<form>
  <img id="myImage" src="http://jsfiddle.net/img/logo.png" />
  <p>Click the buttons below to handle animation</p>
  <input type="button" value="Start" onclick="moveRight();" />
  <input type="button" value="Reset" onclick="reset();" />
</form>

如何使动画与上一行一起工作?

您有一些错误

  1. onclick="Reset();"而非onclick="reset();"

  2. parseInt(imgObj.style.left.replace("px",""))而非parseInt(imgObj.style.left)

  3. imgObj.style.right总是",你必须设置一些类似imgObj.style.left.replace("px","")>200 的东西

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.replace("px","")) + 10 + 'px';
  
  animate = setTimeout(moveRight, 2000); // call moveRight in 20msec
 
  if (parseInt(imgObj.style.left.replace("px",""))+ imgObj.width>= window.innerWidth) {
    Reset();
  }
}
function Reset(){
 clearTimeout(animate);
 imgObj.style.left = '0px';
}
window.onload = init;
<form>
  <img id="myImage" src="http://jsfiddle.net/img/logo.png" />
  <p>Click the buttons below to handle animation</p>
  <input type="button" value="Start" onclick="moveRight();" />
  <input type="button" value="Reset" onclick="Reset();return false;" />
</form>