JavaScript 尝试移动带有事件的图像
JavaScript Trying to move a image with events
我正在尝试使用 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>
工作小提琴。
-
您应该将标记放在脚本末尾之后(标记
</script>
之后)</body>
。 -
变量应该在函数外部之前定义,这样你就不会在每次调用中重置它们:
var the_timer, x_position = 0, the_image; function do_timer() { ....
-
在函数外设置图像一次:
the_image = document.getElementById("the_image");
-
您需要在位置值
x_position
后添加单位符号px
,因此它将是:the_image.style.left = x_position+'px';
-
如果可以分离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';
相关文章:
- 无法在java脚本中调用图像的点击事件函数
- 如何使用更新图像源以响应新闻事件
- 正在捕获动态更改其源的图像的加载事件
- 如何在asp:linkButton上显示鼠标悬停事件上的图像
- 在onmouseover事件中更改图像,并为每个事件设置中断/间隔
- 如何通过一个onclick事件更改两个单独的图像
- 如何使用onclick事件点击一个图像,并让它更改同一网页上的另一个图像
- 使用事件侦听器更改图像
- HTML5/JavaScript图像点击事件
- 使用单击事件如何更改图像
- 获取图像宽度的最早事件
- 使用完整日历在网站上获取并显示来自Google日历事件的附加图像
- 如何使用 OnClick 事件更改结构 JS 的覆盖图像
- 单击图像滑块计时器的事件
- 如何在鼠标移动事件时更改图像的窗口中心和宽度
- iFrame.load事件未等待预加载图像完成
- 创建随机图像交换并禁止鼠标悬停事件
- 单击事件,将图像从一个表放到另一个表中.Javascript、HTML
- 单击Eveent以在Jquery中自动更改事件图像
- Javascript定时事件/图像