jQuery在第二次点击时反转动画

我有一个div元素,在点击事件中,链接滑入。这很好用,除了我现在试图得到它,以便如果第二次点击链接,动画将反转到其原始状态。

我曾尝试在链接中添加一个类,但是当动画运行时,它最终会执行相同的动画但向后移动。

$('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; }); 

处理此问题的最简单方法是使用jQuery切换。 这允许您通过备用点击激活两个function。

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

……还有一个快速的jsFiddle来展示 。

请注意,这使用了jQuery的切换事件处理程序 ,而不是同名的动画效果。

注意#2:根据文档,在jQuery 1.9中删除了toggle()。 (也就是说,允许您传递通过备用点击激活的多个function的方法签名。)

首先,你错过了一个。 在addClass行中。 这是正确的版本:$(’a.contact’)。addClass(’open’);

无论如何,我会这样做:

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

您需要与live函数绑定的原因是,当常规.click()绑定发生时,类“open”不会添加到任何元素。

在这里阅读有关实时方法的信息: http : //api.jquery.com/live/

 $('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; });