简体   繁体   English

如何优化此jQuery代码?

[英]how to optimize this jQuery code?

I have some experimental script, that makes animation of ul list element background-position, when list element is hovered. 我有一些实验脚本,当列表元素悬停时,它使ul列表元素的背景位置动画化。 Is there another way to manage this task ? 还有另一种方法来管理此任务吗? or just optimize this code ? 还是只是优化此代码?

http://jsfiddle.net/jurisKaste/nDgSE/ http://jsfiddle.net/jurisKaste/nDgSE/

var c = 0;
var ids;
$(document).ready(function(){
  $("li.animate").hover(
    function () {
      var param = '0 0';
      ids = setInterval(function() {
        if ( c > 4 ) {
          c = 1;
          param = '0 0';
        }
        else {
          param = (-100 * c++ ) + 'px 0';
          //alert(param);
        }

        $('.animate').css('backgroundPosition', param);
        //$('#foo').fadeOut();
      }, 40);
    },
    function () {
      $('.animate').css('backgroundPosition', '0 0');
      clearInterval(ids);
    }
  );
});

As the basic optimization code, I could only reposition the jQuery statement where the " css() " method is called in the first function section. 作为基本的优化代码,我只能在第一个函数部分中重新定位在其中调用“ css()方法”的jQuery语句。

Hope it helps. 希望能帮助到你。

Change the background to a gif when hovered. 悬停时将背景更改为gif。 Best preformance you will get. 您将获得最佳性能。

var c = 0,
    ids;

$(function(){
    $("li.animate").hover(function () {
        ids = setInterval(function() {
            $('.animate').css('backgroundPosition', ((++c==4) && (c=0), (-100 * c) + 'px 0'));
        }, 40);
      }, function () {
          $('.animate').css('backgroundPosition', '0 0');
          clearInterval(ids);
      }
    );
});

The best way to optimize a 40 millisecond timer interval is to not call expensive jQuery functions within it. 优化40毫秒计时器间隔的最佳方法是不要在其中调用昂贵的jQuery函数。 Store the call to $('.animate') in a variable outside the interval function, then loop through it with for like a normal array, and use standard DOM properties to change the styles of each element. 存储呼叫到$('.animate')通过将其与在一个可变的间隔功能外,然后循环for像一个正常的阵列,并使用标准的DOM属性来改变风格的每个元素的。 That's the gist of it, I added in some code reorganization to make things a bit simpler as well. 这就是要点,我添加了一些代码重组以使事情也更简单。

var c = 0, ids;
$(document).ready(function(){
  $("li.animate").hover(function () {
    var ani = $('.animate'), l = ani.length;

    ids = setInterval(function() {
      var i, param;
      if ( c >= 5 ) {
        c = 1;
        param = '0 0';
      } else {
        param = (-100 * c++) + 'px 0';
      }

      for (i=0; i<l; i++) {
        ani[i].style.backgroundPosition = param;
      }
    }, 40);

  }, 
  function () {
    $('.animate').css('backgroundPosition', '0 0');
    clearInterval(ids);
  }
);});

Try it: http://jsfiddle.net/nDgSE/4/ 试试看: http : //jsfiddle.net/nDgSE/4/

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

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