根据style.right重置位置

时间:2015-12-27 16:05:27

标签: javascript html css animation css-animations

当图像到达屏幕的最右边时,我是trying to reset animation

没有这条线,一切都很完美:

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 个答案:

答案 0 :(得分:2)

你有一些错误

  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

  4. 这样的东西

    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>