本文介绍了如何为动态创建的不同组件重用相同的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个post按钮在我的网页上点击它,我得到一个鱼< div> 组件随机移动。我想创建一个通用代码,以便在点击post按钮创建的许多鱼随机使用通用代码,以提高效率。
I have a post button in my page on click of it I get a fish <div> component which moves randomly. I want to create a generic code so that many fishes which are created on click of post button move randomly using a generic code so that the efficiency increases.
你能帮助我在开发一个代码来动画我的鱼动态为多个鱼。可重用代码是我正在寻找的。
Can you please help me in developing a code to animate my fish dynamically for multiple fishes. Reuseable code is what I'm looking for.
<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)}); }
任何时候点击按钮一个新的鱼插入和动画
something like this. Any time you click button a new fish is inserted and animated
更多推荐
如何为动态创建的不同组件重用相同的代码?
发布评论