繁体   English   中英

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

[英]jQuery reversing animation on second click

我有一个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切换。 这允许您通过备用点击激活两个功能。

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

......还有一个快速的jsFiddle来展示

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

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

首先,你错过了一个。 在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;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM