我需要将一个div从屏幕的右边移到左边,但是同时使用经典的JS和jQuery会让它变得不稳定:
我的div:
<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. I尝试修改div,但它并没有真正提高性能。
所以我的问题是:让这些div顺利移动的最好方法是什么?
发布于 2011-03-07 03:09:26
你问我一个提高速度的例子,我不是专家,但我会这样做:
setInterval与字符串函数一起使用,它们必须通过eval才能运行,因此请使用以下代码。事实上,我根本不会在主循环中使用setInterval (参见第三点)。setInterval(doSomething,100)
var lisp = $('#lisp1');function move() { var pos = parseInt( lisp.css("right"),10 );//始终使用基数lisp.css("right",pos + 10 + "px");}
function move(){ $(".lisp").each(function(){ pos = parseInt( $(this).css("right“));if (pos > width) $(this).remove();else $(This).css(”pos+speed+“,pos+speed+"px") });$(".bonus").each(function(){ pos =parseInt($(This).css(”right“);if (位置>宽度)$(此).remove();else $(此).css(“right”,pos+speed+"px") });$(“.special”).each(){ 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);} //用这个代替setInterval() }
这仍然不是很理想,因为您的代码不断添加越来越多的对象。它应该是有限的,因为有一次我在屏幕上有超过200个对象,页面变得爬行。这也是我为什么要在最后一行使用setTimeout而不是您使用的setInterval的原因,因为在您希望它重新启动之前,脚本可能没有遍历所有元素。
我相信还有其他人可以添加更多的点来进一步优化我或你的代码:)
https://stackoverflow.com/questions/5210981
复制相似问题