Изменить с onclick на onload

Я хотел бы анимировать изображение, чтобы прокрутить страницу. В настоящее время у меня есть версия onClick этого ниже, но я хотел бы, чтобы она автоматически запускалась при загрузке страницы.

Я попытался добавить onload='moveRight()' в теге body, но я получаю сообщение об ошибке:

'не может прочитать тип свойства' 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 ответ

Решение

Добавить другую функцию для вызова init а также moveRight on onload. Модифицируйте свой код, как показано ниже:

<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>
Другие вопросы по тегам