我有一个按钮点击其中出现一条鱼,它应该随机放在一个容器上的随机位置。但在我的代码中它只是动画一次而不是重复overand overagain。我希望我的函数是通用的,这样它就可以在很多鱼上运行并且是高效的代码。
HTML:
<input type="button" value="Post" class="post-button" />
jQuery:
var idgenerated=0;
$('.post-button').on('click',function(e){
//$('#container img:last-child').append('<div class="small-fish"> </div>');
$('#rightarrow').after('<div class="fishhatch" id="'+idgenerated+'"></div>');
$('.pop-up-selectCategory').hide();
$('.oyster').removeClass('oyster-click');
animatenewfish(idgenerated);
idgenerated++;
});
function animatenewfish(idgenerated) {
console.log("hi");
var Fishv1 = $("#"+idgenerated),
theContainer = $("#container"),
maxLeft = theContainer.width() - Fishv1.width()-100,
maxTop = theContainer.height() - Fishv1.height()-100,
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop),
imgRight = "Assets/R1gif.gif",
imgLeft = "Assets/FIsh1.gif";
console.log(maxLeft+"max");
console.log(leftPos+"travel");
if (Fishv1.position().left < leftPos) {
Fishv1.css("background-image",'url("' + imgRight + '")');
} else {
Fishv1.css("background-image",'url("' + imgLeft + '")');
}
Fishv1.animate({
"left": leftPos,
"top": topPos
}, 18000, animatenewfish);
}
答案 0 :(得分:0)
将动画放入
setInterval(function(){
Fishv1.animate({
"left": leftPos,
"top": topPos
}, 18000, animatenewfish(idgenerated));
},18000);
所以它会在每18000
毫秒后调用。
答案 1 :(得分:0)
更改代码您调用函数的位置
此代码将每隔500
ms调用一次函数。
/*Jquery Code*/
var idgenerated=0;
$('.post-button').on('click',function(e){
//$('#container img:last-child').append('<div class="small-fish"> </div>');
$('#rightarrow').after('<div class="fishhatch" id="'+idgenerated+'"></div>');
$('.pop-up-selectCategory').hide();
$('.oyster').removeClass('oyster-click');
setInterval(function() { animatenewfish(idgenerated); }, 500);
idgenerated++;
});
答案 2 :(得分:0)
animate采用可选的回调
Fishv1.animate({
"left": leftPos,
"top": topPos
}, 18000, animatenewfish(idgenerated));