我的页面上有一个发布按钮,点击它我得到一条鱼 <div>
随机移动的组件。我想创建一个通用代码,以便通过单击发布按钮创建的许多鱼使用通用代码随机移动,从而提高效率。
你能帮我开发一个代码来为多条鱼动态地制作我的鱼的动画吗?我正在寻找可重用的代码。
<section class="main-content" id="container">
<input type="button" value="Post" class="post-button" />
<img src="Assets/Arrow.png" class="right-arrow" alt="arrow" id="rightarrow" />
</section>
$('.post-button').on('click',function(e){
$('#rightarrow').after('<div class="fishhatch" ></div>');//new fish created
animatenewfish();//animation to move the fish randomly in my container
});
/*Aniamting the fish*/
function animatenewfish() {
var Fishv1 = $(".fishhatch"),
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)+100,
imgRight = "Assets/R1gif.gif",
imgLeft = "Assets/FIsh1.gif";
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);
}
最佳答案
$('.post-button').on('click',function(e){
var new_fish = $('<div class="fishhatch" ></div>').insertAfter($('#rightarrow'));
animatenewfish(new_fish);
});
function animatenewfish(fish) {
var Fishv1 = fish,
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)+100,
imgRight = "Assets/R1gif.gif",
imgLeft = "Assets/FIsh1.gif";
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, function(){animatenewfish(Fishv1)});
}
是这样的。每当您单击按钮时,都会插入一条新鱼并制作动画
关于jquery - 如何为动态创建的不同组件重用相同的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23628449/