简体   繁体   中英

Moving div randomly around the page with javascript

I am making a game with Javascript and Jquery where the player can buy fish and they swim around in their tank. I want <div id="goldfish"><img src="fish/goldfish_l.gif"/></div> to move around inside of <div id="container"> I also want to change the img src to fish/goldfish_r when the fish moves right. So far I have tried:

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

but that just makes it disappear then reappear somewhere else.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM