gpt4 book ai didi

javascript - 使用javascript在页面上随机移动div

转载 作者:行者123 更新时间:2023-11-29 19:46:00 25 4
gpt4 key购买 nike

我正在使用 Javascript 和 Jquery 制作一款游戏,玩家可以在其中购买鱼,然后在鱼缸中游来游去。我要<div id="goldfish"><img src="fish/goldfish_l.gif"/></div><div id="container"> 内部移动我还想在鱼向右移动时将 img src 更改为 fish/goldfish_r。到目前为止我已经尝试过:

function moveDiv() {
var $span = $("#goldfish");

$span.fadeOut(1000, 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(1000);
});
};
moveDiv();setInterval(moveDiv, 5000);

但这只会让它消失然后重新出现在其他地方。

最佳答案

你很接近。您不需要淡出和淡入,您可以简单地使用函数的回调来循环。

Fiddle .

function AnimateIt() {
var theDiv = $("#the-div"),
theContainer = $("#container"),
maxLeft = theContainer.width() - theDiv.width(),
maxTop = theContainer.height() - theDiv.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop);

if (theDiv.position().left < leftPos) {
theDiv.removeClass("left").addClass("right");
} else {
theDiv.removeClass("right").addClass("left");
}

theDiv.animate({
"left": leftPos,
"top": topPos
}, 1200, AnimateIt);
}
AnimateIt();

如您所见,向左或向右移动时背景会发生变化。我已经用一个类完成了这个,所以你可以很容易地改变背景图像,但如果你真的想改变源,你可以这样做:

Fiddle .

function AnimateIt() {
var theDiv = $("#the-div"),
theContainer = $("#container"),
maxLeft = theContainer.width() - theDiv.width(),
maxTop = theContainer.height() - theDiv.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop),
imgRight = "http://f00.inventorspot.com/images/goldfish.jpg",
imgLeft = "http://2.bp.blogspot.com/-F8s9XEIBSsc/T41x37x9w1I/AAAAAAAAB9A/cDfFJLCERII/s1600/Goldfish-1600x1200.jpg";

if (theDiv.position().left < leftPos) {
theDiv.attr("src", imgRight);
} else {
theDiv.attr("src", imgLeft);
}

theDiv.animate({
"left": leftPos,
"top": topPos
}, 2000, AnimateIt);
}
AnimateIt();

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

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