How to reuse the same code for different component

2019-03-06 20:00发布

问题:

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);
}

回答1:

$('.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