为什么这个jQuery .animate调用这么慢?

时间:2009-11-26 01:03:50

标签: javascript jquery jquery-animate

大家好我有一个很直接的功能

enableModule : function(moduleName){
        var module = $('div#'+moduleName);
        console.log('enabling '+moduleName);
        console.time('animate');
        module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');});
        module.find('.disabled_sheild').remove();
        module.removeClass('disabled');
        console.log('end of enable Module');
    }

动画的自我,不透明度的变化,非常快,但是有一个延迟调用它。 console.time()报告的时间为2540MS及更高。我想这可能是因为div#模块和它的孩子一起被动画了?但是这个剂量是有意义的,因为我有另一个功能“disableModule”,它反过来做同样的事情并以合理的速度运行。

这是禁用模块功能,相当多,但返回时间约为242毫秒

disableModule : function(moduleName){
      $('div#'+moduleName+', div.'+moduleName).each(function(){
        var module = $(this);
        module.prepend('<div class="disabled_sheild"></div>');
        var sheild = module.find('.disabled_sheild');
        sheild.css({'position' : 'absolute', 'z-index' : '200'});
        sheild.width(module.width());
        sheild.height(module.height());
        jQuery.each(jQuery.browser, function(i) {
            if($.browser.msie){
               //module.css("display","none");
               //if using ie give sheild a transparent background layout
            }else{
              console.time('animate');
              module.animate({'opacity' : '0.5'}, function(){ console.timeEnd('animate');});
            }
          });
      });
    }

2 个答案:

答案 0 :(得分:3)

经过一些艰苦的故障排除后,我将其跟踪为禁用方法中浏览器检测循环的问题:

  jQuery.each(jQuery.browser, function(i) {
      if($.browser.msie){
         //module.css("display","none");
         //if using ie give sheild a transparent background layout
      }else{
        console.time('animate');
        module.animate({opacity : 0.5}, 200, function(){console.timeEnd('animate');});
      }
    });

评论这个区块让一切都变得快速。在尝试优化其他所有内容之后,我几乎把头发拉了出来。

答案 1 :(得分:1)

您是否尝试过简单地重新定位它们?

module.find('.disabled_sheild').remove();
module.removeClass('disabled');
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');});

动画是异步发生的,findremove方法可能会消耗资源(特别是因为find遍历DOM树),否则可能会用于动画。

此外,由于您在disable方法中动态创建“禁用屏蔽”,因此可以将其保存

module.data("disabledShield", module.prepend('<div class="disabled_sheild"></div>'));

并在enable方法中使用该引用以避免DOM遍历

module.data("disabledShield").remove();
module.removeClass('disabled');
module.animate({'opacity' : '1.0'}, 300, function(){console.timeEnd('animate');});

(有关$.data

的文档,请参阅http://docs.jquery.com/Internals/jQuery.data