我有这段代码,据说可以使图像在页面中移动,但是它不会移动就可以识别错误。

谢谢。

我的HTML:

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


我的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>


我的CSS:

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

最佳答案

尝试下面的代码,它可能会帮助您。



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>

关于javascript - 随机移动图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35457638/

10-16 18:59