如何使用 javascript 移动图像?
我正在开发一个简单的网络测验并使用javascript,我想创建一个效果,当用户达到特定级别或分数时,显示一个小图像(1UP),该图像在“游戏甲板”周围徘徊;用户只需及时点击它即可获得额外的生命。
你知道有什么 Jquery 插件或 javascript 片段可以实现这样的效果吗?
I'm developing a simple web quiz and using javascript, I would like to create an effect that displays a small image (1UP) that wanders around the "game deck" when users reach a specific level or score; user could gain an extra life simply clicking on it in time.
Do you know any Jquery plugin or javascript snippet to achieve an effect like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,做到这一点非常容易:
创建元素:
设置其源:
绝对定位它,这样:(
显然,使用您想要的任何坐标和大小。)
您可能想确保它出现在其他东西之上:
将其添加到文档:
移动它
使用
window.setInterval
(或setTimeout
,具体取决于您想要的方式)通过更改其style.left
来移动它code> 和 style.top 设置。您可以使用 Math.random 获取 0 到 1 之间的随机浮点数,然后将其相乘并通过 Math.floor 运行以获取整数以更改您的坐标。示例
这会在 50,50 处创建一个图像,并以一种非常不稳定的随机方式对其进行动画处理(以一种非常紧张的随机方式;我没有花任何时间让它看起来很漂亮),每五分之一秒一次,持续 10 秒,然后将其删除:(
我更喜欢重新通过
setTimeout
[如上所述] 使用setInterval
安排每次迭代,但这完全由您决定,如果使用setInterval
,请记住间隔句柄 [。从setInterval
返回值,并在完成后使用window.clearTimeout
取消它。)以上是原始 DOM/JavaScript; jQuery 提供了一些帮助程序,使其变得更简单,但正如您所看到的,即使没有,它也非常简单。
It's actually surprisingly easy to do this:
Create the element:
Set its source:
Position it absolutely and such:
(Obviously, use whatever coordinates and size you want.)
You may want to make sure it appears above other things:
Add it to the document:
Move it around
Use
window.setInterval
(orsetTimeout
depending on how you want to do it) to move it around by changing itsstyle.left
andstyle.top
settings. You can useMath.random
to get a random floating point number between 0 and 1, and multiply that and run it throughMath.floor
to get a whole number for changing your coordinates.Example
This creates an image at 50,50 and animates it (in a very jittery random way; I didn't spend any time making it look nifty) every fifth of a second for 10 seconds, then removes it:
(I prefer re-scheduling on each iteration via
setTimeout
[as above] to usingsetInterval
, but it's totally your call. If usingsetInterval
, remember the interval handle [return value fromsetInterval
and usewindow.clearTimeout
to cancel it when you're done.)The above is raw DOM/JavaScript; jQuery offers some helpers to make it a bit simpler, but as you can see, it's pretty straightforward even without.
还有一个 jQuery 函数可用于移动物体。
请参阅此示例:
http://api.jquery.com/animate/
There's also a jQuery function that can be used to move thing's around.
See this for examples:
http://api.jquery.com/animate/