从onclick更改为onload

时间:2014-03-04 10:26:53

标签: javascript image scroll

我想动画一个图像以滚动页面。我目前有一个onClick版本,但希望它能在页面加载时自动运行。

我试过在body标签中添加onload ='moveRight()',但是我收到错误:

'无法读取'null''的属性类型

使用Javascript:

<script type="text/javascript">
    <!--
    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) + 1 + 'px';
       animate = setTimeout(moveRight,400); // call moveRight in 400msec
    }
    function stop(){
       clearTimeout(animate);
       imgObj.style.left = '0px'; 
    }
    window.onload =init;
    //-->
</script>

HTML

<html>

   <head>

     <title>JavaScript</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)

在onload上添加另一个函数来调用initmoveRight。修改你的代码,如下所示:

<script type="text/javascript">

    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) + 1 + 'px';
        animate = setTimeout(moveRight, 400); // call moveRight in 400msec
    }
    function stop() {
        clearTimeout(animate);
        imgObj.style.left = '0px';
    }
    function InitMove() {
        init();
        moveRight();
    }
    window.onload = InitMove;

</script>