gpt4 book ai didi

javascript - 使图像在div内随机移动

转载 作者:行者123 更新时间:2023-11-30 10:31:11 24 4
gpt4 key购买 nike

我正在创建一个简单的游戏,我目前被困在一个名为“盒子”的 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

Here's a demo to get you in the right track .

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com