簡體   English   中英

使圖像隨機移動到div內

[英]make an image move inside a div randomly

我正在創建一個簡單的游戲,我現在卡在一個叫做“盒子”的div里面,當游戲開始降落傘時,里面的圖像稱為“降落傘”應該在div的邊框內隨機移動

我的代碼:

 <div id="box">


    </div>

 <script type="text/javascript">
 var ToAppend = "<img src='Parachute.gif' width='25px' height='25px' class='Parachute' />  ";
        setInterval(function () {
            for (var i = 1; i <= 2; i++) {
                $("#box").append(ToAppend);
                MoveParticles();
            }
        }, 3000);

        function MoveParticles() {
               $(".Parachute").each(function () {
                var x = Math.floor(Math.random() * 400);
                var y = Math.floor(Math.random() * 400);

                $(this).animate({ "left": x + "px" }, "slow");
                $(this).animate({ "top": y + "px" }, "slow");
            });
        }
       <script>

你似乎在動畫#box ,而不是.Parachute

這是一個讓您走上正確軌道的演示

//let's build the chutes
for (var i = 0; i < 50; ++i) {
    $('<div/>', {
        class: 'chute'
    }).appendTo('#box');
}

//cache a few static values
var box = $('#box');
var width = box.width();
var height = box.height();
var chute = $('.chute');

//our main animation "loop"

chute.each(function foo() {

    //generate random values
    var top = (Math.random() * height) | 0;
    var left = (Math.random() * width) | 0;
    var time = Math.random() * (800 - 400) + 400 | 0;

    //animate
    //we introduce a random value so that they aren't moving together
    //after the animation, we call foo for the current element
    //to animate the current element again
    $(this).animate({
        left: left,
        top: top
    }, time, foo);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM