sys*_*out 3 javascript jquery graphic-effects
我正在开发一个简单的网络测验并使用javascript,我想创建一个效果,显示一个小图像(1UP),当用户达到特定级别或分数时,它会在"游戏套牌"周围徘徊; 用户只需及时点击即可获得额外的生命.
你知道任何Jquery插件或javascript片段来实现这样的效果吗?
这实际上非常容易:
img = document.createElement('img');
Run Code Online (Sandbox Code Playgroud)
img.src = "myimage.png";
Run Code Online (Sandbox Code Playgroud)
img.style.position = "absolute";
img.style.left = "50px";
img.style.top = "50px";
img.style.width = "50px"; // Make these match the image...
img.style.height = "50px"; // ...or leave them off
Run Code Online (Sandbox Code Playgroud)
(显然,使用你想要的任何坐标和大小.)
您可能希望确保它出现在其他内容之上:
img.style.zIndex = 100; // Or whatever
Run Code Online (Sandbox Code Playgroud)
document.body.appendChild(img);
Run Code Online (Sandbox Code Playgroud)
使用window.setInterval(或setTimeout取决于你想如何做到这一点),通过改变其移动它style.left和style.top设置.您可以使用Math.random获取0到1之间的随机浮点数,并将其相乘并运行它Math.floor以获得用于更改坐标的整数.
这会创建一个50,50的图像并以5秒钟的每秒五分之一的时间(以非常紧张的随机方式;我没有花费任何时间让它看起来很漂亮)动画它然后将其移除:
function createWanderingDiv() {
var img, left, top, counter, interval;
img = document.createElement('img');
img.src = "myimage.png";
left = 200;
top = 200;
img.style.position = "absolute";
img.style.left = left + "px";
img.style.top = top + "px";
img.style.width = "200px"; // Make these match the image...
img.style.height = "200px"; // ...or leave them out.
img.style.zIndex = 100; // Or whatever
document.body.appendChild(img);
counter = 50;
interval = 200; // ms
window.setTimeout(wanderAround, interval);
function wanderAround() {
--counter;
if (counter < 0)
{
// Done; remove it
document.body.removeChild(img);
}
else
{
// Animate a bit more
left += Math.floor(Math.random() * 20) - 10;
if (left < 0)
{
left = 0;
}
top += Math.floor(Math.random() * 10) - 5;
if (top < 0)
{
top = 0;
}
img.style.left = left + "px";
img.style.top = top + "px";
// Re-trigger ourselves
window.setTimeout(wanderAround, interval);
}
}
}
Run Code Online (Sandbox Code Playgroud)
(我更喜欢通过setTimeout[如上所述] 重新安排每次迭代使用setInterval,但它完全是你的调用.如果使用setInterval,请记住间隔句柄[返回值,setInterval并window.clearTimeout在完成后用它取消它.)
以上是原始DOM/JavaScript; jQuery提供了一些帮助,使它更简单,但正如你所看到的,即使没有它,它也非常简单.