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

标签 jquery css html animation core-animation

我的页面上有一个发布按钮,点击它我得到一条鱼 <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/

相关文章:

javascript - 单击 HTML5 Canvas

javascript - Jquery 导航栏动画无法正常工作

jquery - 动态填充 Chart.js 图表上的颜色

jquery - 如何使用 jQuery 注入(inject)表单值?

JavaScript sleep /等待,然后再继续

css - Bootstrap 网格系统 : column classes without a number

html - 浏览器位置 :absolute and decimal truncation?

jquery - CSS 从左到右滑动过渡

android - 嵌入 WebKit 是在 Android 应用程序中显示超链接对象和图像列表的正确解决方案吗?

javascript - 如何将具有 contenteditable 列的表保存到本地存储中