简体   繁体   中英

Move image randomly

I have this code that supposedly makes the image move around the page but It doesnt moves can someone identify the error.

Thanks.

My HTML :

<div id="container"> <span id="random"><img src="poke.png"></span> </div>

My JS :

<script>
function moveDiv() {
    var $span = $("#random");

    $span.fadeOut(270, 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(270);
    });
};

moveDiv();
setInterval(moveDiv, 270);
</script>

My CSS :

<style>span { display: inline-block; position: absolute;}</style>

try with below code, it might help you.

 function moveDiv() { var $span = $("#random"); $span.fadeOut(270, 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(270); }); }; moveDiv(); setInterval(moveDiv, 270); 
 span { display: inline-block; position: absolute;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="container"> <span id="random"><img src="http://hiroki.jp/wp-content/uploads/2011/06/google-chrome-logo-100x100.png"></span> </div> 

As you can see here your code works fine. The reason why in your case the code is not working is beacuse the script is not running when all of the DOM is loaded.

You can wrap your script code in document ready

$(document).ready()

Like the above comments mentioned, this ensures the code is ran when the DOM is loaded.

It works just include the jQuery into your code

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
You can wrap your script code in document ready too.

 $(document).ready() 

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