我需要从屏幕的右侧向左侧移动一个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顺利移动的最佳方法是什么?
解决方法
你问我一个提高速度的例子,我不是专家,但我会这样做:
>不要将setInterval与字符串函数一起使用,它们必须通过eval运行才能运行,所以请改用它.事实上,我根本不会对主循环使用setInterval(参见第3点).
setInterval(doSomething,100)
>存储您将多次使用的对象(特别是在不断循环的函数中).即使这个例子也不理想:
var lisp = $('#lisp1');
function move()
{
var pos = parseInt( lisp.css("right"),10 ); // always use a radix
lisp.css("right",pos + 10 + "px");
}
>对于不断循环的函数,尽可能简洁明了,省去额外的函数调用.从你的第二个链接,我压缩了这段代码:
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的原因,因为在你希望它再次启动之前,脚本可能没有循环遍历所有元素.
我相信还有其他人可以添加更多的点来优化我或你的代码:)