jQuery reversing animation on second click

梦想与她 提交于 2019-11-27 18:47:14

问题


I have a div element, that on click event, a link slides in. This works great, except I am now trying to get it so that if the link is clicked a second time, the animation reverses to its original state.

I have tried to add a class to the link, but when the animation runs it ends up doing the same animation but backwards.

    $('a.contact').click(function() {
        $('#contact').animate({marginLeft:'500px'}, {queue:false, duration:'7000'});
        $('#contact').animate({width:'500px'}, {duration:'7000'});
        $('a.contact').css()
        $('a.contact').animate({marginLeft:'-500px'}, '250');
        $('a.contact')addClass('open');
    return false;
});

回答1:


The easiest way to handle this would be to use jQuery toggle. This allows you to activate two functions on alternate clicks.

$('a.contact').toggle(
function(){
    // odd clicks
},
function(){
    // even clicks
});

...And a quick jsFiddle to demonstrate.

Note that this uses jQuery's toggle event handler, not the animation effect of the same name.

Note #2: As per the documentation, toggle() was removed in jQuery 1.9. (That is, the method signature that allowed you to pass multiple functions which were activated on alternate clicks.)




回答2:


First of all you are missing a . in the addClass line. This is the correct version: $('a.contact').addClass('open');

Anyway, I would do like this:

// Bind the click event with the live function

$('a.contact:not(.open)').live('click', function() {
    // Animate box as wanted and add a class to indicate that the box is open.
    // ... Code to animate goes here ...
    $(this).addClass('open');
});

$('a.open').live('click', function() {
    // Reverse animation and remove class
    // ... Code to reverse animation goes here ...
    $(this).removeClass('open');
});

The reason that you need to bind with the live function is that the class "open" is not added to any elements when the regular .click() binding takes place.

Read about the live method here: http://api.jquery.com/live/




回答3:


$('a.contact').click(function(e) {
   e.stopPropagation();
   var dir = '';

   if ($(this).hasclass('to-left'))
   {
      dir = 'to-rigth';
      $(this).removeClass('to-left');
   } 
   else //ini or has class to rigth
   {
      dir = 'to-left';
      $(this).removeClass('to-rigth');
   }

   dir = $(this).addclass(dir);

   if (dir=='to-left')
   {
      //you code to left
   }
   else 
   {
      //you code to rigth
   }

    return false;
});


来源:https://stackoverflow.com/questions/2132090/jquery-reversing-animation-on-second-click

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