jQuery animate on click multiple times

我们两清 提交于 2019-12-11 10:25:32

问题


I am currently building a web app where I need to randomly generate text content and switch its color every time a button is clicked.

At the moment, I'm trying to add some kind of animation to it, and here's what I'd like to obtain each time the button is clicked:

  1. The random class is added
  2. The div pops up from the bottom of the page with its opacity increasing

I prepared a simplified JSFiddle to illustrate my point below.

Example

http://jsfiddle.net/cdacx0tn/11/

var color = ["blue", "purple", "green"];

$("#try-me").click(function() { 
    var colorClass = color[Math.floor(Math.random()*color.length)];

    $("#content")
    .removeClass()
    .addClass(colorClass)
    .animate({
        "margin-top": "50px",
        "opacity": "1"
    }, 700);
});

I managed to get this done when the button is clicked once but I can't figure out how to do this each time it is clicked.

I want to add that I'm not a professional developper so please be indulgent.

Thanks for your help.


回答1:


Set the CSS of the element before animating it, making sure it's back at it's initial position with marginTop and can't be seen using opacity.

Add a stop() in their to prevent animations being queued and there you have it:

var color = ["blue", "purple", "green"];

$("#try-me").click(function() { 
    var colorClass = color[Math.floor(Math.random()*color.length)];
    $("#content")
        .css({opacity:0,marginTop:200})
        .removeClass()
        .addClass(colorClass)
        .stop(true,false)
        .animate({
            "margin-top": "50px",
            "opacity": "1"
        }, 700);
});

JSFiddle

Documentation:

  • css()
  • stop()



回答2:


try

 var color = ["blue", "purple", "green"];

    $("#try-me").click(function() { 
        var colorClass = color[Math.floor(Math.random()*color.length)];
        $("#content").css({ "margin-top": "200px", "opacity": "0"});  // reset the margin and opacity value
        $("#content")
        .removeClass()
        .addClass(colorClass)
        .animate({
            "margin-top": "50px",
            "opacity": "1"
        }, 700,function(){


        });
    });

DEMO




回答3:


Re initialize the margin-top of #content to 200px after animation :

     $("#content").css("margin-top","200px");

DEMO HERE



来源:https://stackoverflow.com/questions/25283571/jquery-animate-on-click-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!