JavaScript 尝试移动带有事件的图像

JavaScript Trying to move a image with events

本文关键字:事件 图像 移动 JavaScript      更新时间:2023-09-26

我正在尝试使用 js 脚本移动图像,但它不起作用,控制台不显示任何内容。

<html>
  <body onload ="do_timer()"> 
    <img id="the_image" src="https://s15-us2.ixquick.com/cgi-bin/serveimage?url=http:%2F%2Fstatic.allbackgrounds.com%2Fbg%2Forange.jpg&sp=fe8f01b8441f1d048c52dbd3721287a2" style="position: absolute; left:0px;"> 
  </body>
  <script>
    function do_timer() {
      var the_timer, x_position = 0
      , the_image;
      the_image = document.getElementById("the_image");
      x_position++;
      the_image.style.left = x_position;
      the_timer = setTimeout(do_timer, 50);
    }
  </script>
</html>

工作小提琴

  1. 您应该将标记放在脚本末尾之后(标记</script>之后)</body>

  2. 变量应该在函数外部之前定义,这样你就不会在每次调用中重置它们:

    var the_timer, x_position = 0, the_image;
    function do_timer() {
    ....
    
  3. 在函数外设置图像一次:

    the_image = document.getElementById("the_image");
    
  4. 您需要在位置值x_position后添加单位符号px,因此它将是:

    the_image.style.left = x_position+'px';
    
  5. 如果可以分离CSS代码并避免内联样式,那就更好了:

    #the_image{
       left: 0px;
       position: absolute;
    }
    

完整代码 :

<body onload ="do_timer()"> 
    <img id="the_image" src="http://image.flaticon.com/teams/1-freepik.jpg">
    <script>
        var the_timer, x_position = 0, the_image=document.getElementById("the_image");
        function do_timer() {
          x_position++;
          the_image.style.left = x_position+'px';
          the_timer = setTimeout(do_timer, 50);
        }
    </script>
</body>

希望这有帮助。

var the_timer, x_position = 0, the_image=document.getElementById("the_image");
function do_timer() {
  x_position++;
  the_image.style.left = x_position+'px';
  the_timer = setTimeout(do_timer, 50);
}
#the_image{
  left: 0px;
  position: absolute;
}
<body onload ="do_timer()"> 
  <img id="the_image" src="http://image.flaticon.com/teams/1-freepik.jpg">
</body>

您应该使用 px、cm、em 等单位设置位置。

前任:

element.style.left = x + 'px';