[英]JavaScript Trying to move a image with events
I'm trying to move a image with a js script but it doesnt work, the console dont show anything. 我正在尝试使用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>
You should set the position with a unit like px, cm, em, etc. 您应该使用px,cm,em等单位设置位置。
Ex: 例如:
element.style.left = x + 'px';
Working fiddle . 工作提琴 。
You should place the tag </body>
after the end of script (after tag </script>
). 您应该将标记</body>
放在脚本末尾(标记</script>
)。
The variables should be defined before outside of the function so you will not reset them in every call : 变量应该在函数外部定义,这样您就不会在每次调用时都将其重置:
var the_timer, x_position = 0, the_image; function do_timer() { ....
Set the image one time outside of the function : 在功能之外设置图像一次:
the_image = document.getElementById("the_image");
You need to add the unit sign px
after the position value x_position
so it will be : 您需要在位置值x_position
之后添加单位符号px
,这样它将是:
the_image.style.left = x_position+'px';
Better if you could separate the CSS code and avoid the inline style : 如果可以分隔CSS代码并避免使用内联样式,那就更好了:
#the_image{ left: 0px; position: absolute; }
FULL CODE : 完整代码:
<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>
Hope this helps. 希望这可以帮助。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.