【问题标题】:Why are these Javascript function producing different results?为什么这些 Javascript 函数会产生不同的结果?
【发布时间】:2011-11-09 17:46:43
【问题描述】:

我有一个函数:

var myAnimation = function(){
    $(".next_action").css({'bottom':"-100%","left":"0"}).animate({'bottom':"0"},1000);
    $('.active').animate({'top':"-100%"},1000);
}

这需要两个对象并对其进行动画处理,从而产生滑动效果。

为了获得多方向支持,我将位置封装在参数中:

 var myAnimation = function(inE,outE){
        $(".next_action").css({inE:"-100%","left":"0"}).animate({inE:"0"},1000);
        $('.active').animate({outE:"-100%"},1000);
    }

我现在可以这样称呼:

myAnimation('bottom','top');

就我而言,这些功能应该是完全等价的,但第一个有效,第二个无效。根本没有动画发生,新对象简单地跳到适当的位置。

【问题讨论】:

    标签: javascript jquery function animation


    【解决方案1】:

    {inE:"-100%","left":"0"} 使用键 inE 和键 left 创建一个对象。唯一需要在 JavaScript 中用引号将键括起来的情况是它是保留字(ifelse 等)或包含控制字符(-:{)。

    相反,您需要这样的东西;

    var myAnimation = function(inE, outE) {
        var animObjA = {
            left: 0
        };
        var animObjB = {};
        var animObjC = {};
    
        animObjA[inE] = "-100%";
        animObjB[inE] = "0";
        animObjC[outE] = "-100%";
    
        $(".next_action").css(animObjA).animate(animObjB, 1000);
        $('.active').animate(animObjC, 1000);
    }
    

    其中使用square bracket notation设置对象的属性

    【讨论】:

      猜你喜欢
      • 2015-03-11
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多