2

我正在使用 Javascript 和 Jquery 制作游戏,玩家可以在其中购买鱼并在鱼缸中游来游去。我想<div id="goldfish"><img src="fish/goldfish_l.gif"/></div>在里面移动<div id="container">我还想在鱼向右移动时将 img src 更改为 fish/goldfish_r。到目前为止,我已经尝试过:

function moveDiv() {
    var $span = $("#goldfish");

    $span.fadeOut(1000, function() {
        var maxLeft = $(window).width() - $span.width();
        var maxTop = $(window).height() - $span.height();
        var leftPos = Math.floor(Math.random() * (maxLeft + 1))
        var topPos = Math.floor(Math.random() * (maxTop + 1))

        $span.css({ left: leftPos, top: topPos }).fadeIn(1000);
    });
};
moveDiv();setInterval(moveDiv, 5000);

但这只会让它消失然后在其他地方重新出现。

4

1 回答 1

3

You were close. You don't need to fade out and the fade in and you can simply use the callback of the function to loop.

Fiddle.

function AnimateIt() {
    var theDiv = $("#the-div"),
        theContainer = $("#container"),
        maxLeft = theContainer.width() - theDiv.width(),
        maxTop = theContainer.height() - theDiv.height(),
        leftPos = Math.floor(Math.random() * maxLeft),
        topPos = Math.floor(Math.random() * maxTop);

    if (theDiv.position().left < leftPos) {
        theDiv.removeClass("left").addClass("right");
    } else {
        theDiv.removeClass("right").addClass("left");
    }

    theDiv.animate({
        "left": leftPos,
        "top": topPos
    }, 1200, AnimateIt);
}
AnimateIt();

As you can see, the background changes when going either left or right. I've done this with a class, so you could easily change the background-image, but if you really want to change the source you can do this:

Fiddle.

function AnimateIt() {
    var theDiv = $("#the-div"),
        theContainer = $("#container"),
        maxLeft = theContainer.width() - theDiv.width(),
        maxTop = theContainer.height() - theDiv.height(),
        leftPos = Math.floor(Math.random() * maxLeft),
        topPos = Math.floor(Math.random() * maxTop),
        imgRight = "http://f00.inventorspot.com/images/goldfish.jpg",
        imgLeft = "http://2.bp.blogspot.com/-F8s9XEIBSsc/T41x37x9w1I/AAAAAAAAB9A/cDfFJLCERII/s1600/Goldfish-1600x1200.jpg";

    if (theDiv.position().left < leftPos) {
        theDiv.attr("src", imgRight);
    } else {
        theDiv.attr("src", imgLeft);
    }

    theDiv.animate({
        "left": leftPos,
        "top": topPos
    }, 2000, AnimateIt);
}
AnimateIt();
于 2013-10-30T16:25:59.277 回答