【问题标题】:jQuery reversing animation on second clickjQuery在第二次点击时反转动画
【发布时间】:2010-01-25 12:10:27
【问题描述】:

我有一个 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;
});

【问题讨论】:

  • 如果这是你的代码,你也缺少一个句点,使用链接

标签: javascript jquery jquery-animate


【解决方案1】:

处理此问题的最简单方法是使用 jQuery 切换。这允许您在交替点击时激活两个功能。

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

...还有一个快速的jsFiddle to demonstrate

注意这里使用的是jQuery's toggle event handler,不是同名的动画效果。

注意 #2:根据文档,toggle() 在 jQuery 1.9 中被删除。 (也就是说,允许您传递多个在交替单击时激活的函数的方法签名。)

【讨论】:

    【解决方案2】:

    首先,您缺少一个 .在 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”类没有添加到任何元素。

    在此处了解 live 方法:http://api.jquery.com/live/

    【讨论】:

    • 需要注意的是 .live() 从 jQuery v1.7 开始被弃用,从 v1.9 开始被移除
    【解决方案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;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多