如何为动态创建的不同组件重用相同的代码?

编程入门 行业动态 更新时间:2024-10-24 10:17:51
本文介绍了如何为动态创建的不同组件重用相同的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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

更多推荐

如何为动态创建的不同组件重用相同的代码?

本文发布于:2023-11-29 13:36:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646534.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为   组件   代码   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!