用JS / jQuery移动div的最流畅的方法

时间:2011-03-06 14:15:09

标签: javascript jquery html jquery-animate move

我需要从屏幕的右侧向左侧移动一个div,但是使用经典的JS和jQuery会让它变得生涩:

我的divs:

<div class="lisp" id="lisp0" style="top:100px;">)</div>
<div class="lisp2" id="lisp1" style="top:300px;">)</div>

经典的javascript方法:

function move()
{
  pos = parseInt($("#lisp1").css("right"));
  $("#lisp1").css("right", pos+10+"px");
}
var interval = setInterval("move()",10);

jQuery方法:

$("#lisp0").animate({"left": "-=2200px"}, 10000);

我做了一个webpage来向你展示它是多么生涩。第一步是jQuery(最流畅的),第二步是经典的JS。有几个div(和经典的JS),it starts to be really annoying. 我试图修改jQuery.fx.interval,但它并没有真正提高性能。

所以我的问题是:让这些div顺利移动的最佳方法是什么?

1 个答案:

答案 0 :(得分:5)

你问我一个提高速度的例子,我不是专家,但我会这样做:

  1. 不要将setInterval与字符串函数一起使用,它们必须运行eval才能运行,因此请改用它。事实上,我根本不会使用setInterval作为主循环(参见第3点)。

    setInterval(doSomething, 100)
    
  2. 存储您将多次使用的对象(特别是在不断循环的函数中)。即使这个例子也不理想:

    var lisp = $('#lisp1');
    function move()
    {
     var pos = parseInt( lisp.css("right"), 10 ); // always use a radix
     lisp.css("right", pos + 10 + "px");
    }
    
  3. 对于不断循环的函数,尽可能简洁明了,省去额外的函数调用。从你的第二个链接,我压缩了这段代码:

    function move(){
          $(".lisp").each(function(){
    pos = parseInt($(this).css("right"));
        if (pos > width)
          $(this).remove();
        else
          $(this).css("right", pos+speed+"px")
      });
      $(".bonus").each(function(){
        pos = parseInt($(this).css("right"));
        if (pos > width)
          $(this).remove();
        else
          $(this).css("right", pos+speed+"px")
      });
      $(".special").each(function(){
        pos = parseInt($(this).css("right"));
        if (pos > width)
          $(this).remove();
        else
          $(this).css("right", pos+speed+"px")
      });
    }
    

    进入这个更简洁的版本:

    function move(){
      $(".lisp, .bonus, .special").each(function(){
        var pos = parseInt(this.style.right || 0, 10);
        if (pos > width) {
          $(this).remove();
        } else {
          this.style.right =  pos + speed + "px";
        }
      });
      if (!over) { setTimeout(move, 10); } // use this instead of the setInterval()
    }
    

    它仍然不理想,因为您的代码不断添加越来越多的对象。它应该是有限的,因为有一点我在屏幕上有超过200个对象,页面爬行。这也是我在最后一行使用setTimeout而不是您使用的setInterval的原因,因为在您希望它再次启动之前,脚本可能没有循环遍历所有元素。

  4. 我确信其他人可以添加更多点来优化我或您的代码:)