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

ldi*_*ual 7 html javascript jquery move jquery-animate

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

我的divs:

<div class="lisp" id="lisp0" style="top:100px;">)</div>
<div class="lisp2" id="lisp1" style="top:300px;">)</div>
Run Code Online (Sandbox Code Playgroud)

经典的javascript方法:

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

jQuery方法:

$("#lisp0").animate({"left": "-=2200px"}, 10000);
Run Code Online (Sandbox Code Playgroud)

我做了一个网页,告诉你它是多么生涩.第一步是jQuery(最流畅的),第二步是经典的JS.有几个div(和经典的JS),它开始真的很烦人. 我试图修改jQuery.fx.interval,但它并没有真正提高性能.

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

Mot*_*tie 5

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

  1. 不要使用setInterval字符串函数,它们必须运行eval才能运行,所以请改用它.事实上,我根本不会使用setInterval主循环(参见第3点).

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

    var lisp = $('#lisp1');
    function move()
    {
     var pos = parseInt( lisp.css("right"), 10 ); // always use a radix
     lisp.css("right", pos + 10 + "px");
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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")
      });
    }
    
    Run Code Online (Sandbox Code Playgroud)

    进入这个更简洁的版本:

    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()
    }
    
    Run Code Online (Sandbox Code Playgroud)

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

我敢肯定,还有其他人可以添加更多点来优化我或你的代码:)