How to reuse the same code for different components created dynamically?

前端 未结 1 909
逝去的感伤
逝去的感伤 2021-01-29 08:40

I have a post button in my page on click of it I get a fish

component which moves randomly. I want to create a generic code so that many fishes which ar
相关标签:
1条回答
  • 2021-01-29 09:24
    $('.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

    0 讨论(0)
提交回复
热议问题