3

我正在开发一个简单的网络测验并使用 javascript,我想创建一个效果,当用户达到特定级别或分数时,它会显示一个小图像 (1UP),它会在“游戏牌组”周围徘徊;用户只需及时点击即可获得额外的生命。

你知道任何 Jquery 插件或 javascript 片段来实现这样的效果吗?

4

2 回答 2

8

这样做实际上非常容易:

创建元素:

img = document.createElement('img');

设置其来源:

img.src = "myimage.png";

绝对定位它:

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

(显然,使用您想要的任何坐标和大小。)

您可能希望确保它出现在其他事物之上:

img.style.zIndex = 100; // Or whatever

将其添加到文档中:

document.body.appendChild(img);

左右移动

使用window.setInterval(或setTimeout取决于您想要如何操作)通过更改其style.leftstyle.top设置来移动它。您可以使用Math.random获取 0 到 1 之间的随机浮点数,并将其相乘并运行它Math.floor以获得用于更改坐标的整数。

例子

这会在 50,50 处创建一个图像并对其进行动画处理(以非常紧张的随机方式;我没有花任何时间让它看起来很漂亮)每五分之一秒 10 秒,然后将其删除:

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);
        }
    }
}

setTimeout(与 using 相比,我更喜欢通过[as above]重新安排每次迭代setInterval,但这完全是您的决定。如果 using setInterval,请记住间隔句柄 [return value fromsetIntervalwindow.clearTimeout在完成后用于取消它。)

以上是原始 DOM/JavaScript;jQuery 提供了一些帮助程序使其更简单,但正如您所见,即使没有它也非常简单。

于 2010-01-31T15:28:34.777 回答
2

还有一个 jQuery 函数可以用来移动东西。

请参阅此示例: http ://api.jquery.com/animate/

于 2013-06-03T08:41:11.327 回答