简体   繁体   English

随机移动图像

[英]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 : 我的HTML:

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

My JS : 我的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 : 我的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. 在您的情况下,代码无法正常工作的原因是因为在加载所有DOM后脚本未运行。

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. 就像上面提到的注释一样,这可以确保在加载DOM时运行代码。

It works just include the jQuery into your code 它的工作原理只是将jQuery包含在您的代码中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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