问题描述:

I have called several animations to occur when a button is clicked. I want to toggle these animations, so that the elements return to their starting positions when clicked for a second time.

Here is my script:

$("span.click").click(function() {

$(".map").animate(

{"opacity": "1"}, 200);

});

$("span.click").click(function() {

$(".navigation").animate(

{"bottom": "-100px"}, 200);

});

$("span.click").click(function() {

$(".click").animate(

{"bottom": "150px"}, 200);

});

As you can see, three animations are occurring. What sort of if/else statement needs to be put into place in order to create reversible animations?

Here is a jsfiddle: http://jsfiddle.net/6arjhkzc/2/

网友答案:

jsfiddle demo

$(document).ready(function() {
    $("span.click").click(function() {

        var io = this.io ^= 1; // Simple I/O toggler

      $(".map").animate({"opacity": io ? 1 : 0}, 200);
      $(".navigation").animate({"bottom": io ? -100 : -150}, 200);
      $(".click").animate({"bottom": io ? 150 : 100}, 200);
    });
});

store 1 or 0 inside the clicked button io property (used as Boolean since 0 evaluates as false).
Than using some Conditional Operator ?: you can toggle the desired values.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
http://stackoverflow.com/a/22061240/383904

If you're not confortable with the bitwise XOR operator ^ as toggler, you can always use a standard flip-flap negation (demo):

var io = this.io = !this.io;
相关阅读:
Top