Javascript 从onclick更改为onload

Javascript 从onclick更改为onload,javascript,image,scroll,Javascript,Image,Scroll,我想动画图像滚动整个页面。我目前有一个onClick版本的这个下面,但希望它能自动运行页面加载 我尝试在body标记中添加onload='moveRight()',但出现了一个错误: '无法读取'null'的属性类型' Javascript: <script type="text/javascript"> <!-- var imgObj = null; var animate ; function init(){ imgObj =

我想动画图像滚动整个页面。我目前有一个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>

JavaScript
单击下面的按钮以处理动画


任何帮助都会很好,谢谢。

添加另一个函数以在onload时调用
init
moveRight
。修改代码如下所示:

<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>

var imgObj=null;
变量动画;
函数init(){
imgObj=document.getElementById('myImage');
imgObj.style.position='relative';
imgObj.style.left='0px';
}
函数moveRight(){
imgObj.style.left=parseInt(imgObj.style.left)+1+'px';
animate=setTimeout(moveRight,400);//在400毫秒内调用moveRight
}
函数停止(){
clearTimeout(动画);
imgObj.style.left='0px';
}
函数InitMove(){
init();
moveRight();
}
window.onload=InitMove;
太好了,谢谢:)。为什么它不允许我添加“window.onload=moveRight;”到代码的末尾?理论上,这要求代码执行与函数相同的操作。