使用 JS/jQuery 移动 div 的最流畅方法
我需要将 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);
我做了一个 网页 向您展示它有多不稳定。第一步是使用 jQuery(最流畅的),第二步是使用经典 JS。对于几个 div(和经典的 JS),它开始变得非常烦人。 我尝试修改 jQuery.fx.interval,但它并没有真正提高性能。
所以我的问题是:让这些 div 顺利移动的最佳方法是什么?
I need to move a div from the right to the left of the screen, but using both classic JS and jQuery makes it jerky:
My divs:
<div class="lisp" id="lisp0" style="top:100px;">)</div>
<div class="lisp2" id="lisp1" style="top:300px;">)</div>
Classic javascript method:
function move()
{
pos = parseInt($("#lisp1").css("right"));
$("#lisp1").css("right", pos+10+"px");
}
var interval = setInterval("move()",10);
jQuery method:
$("#lisp0").animate({"left": "-=2200px"}, 10000);
I made a webpage to show you how jerky it is. The first move is with jQuery (the smoothest one), the second one with classic JS. With several divs (and classic JS), it starts to be really annoying.
I tried to modify jQuery.fx.interval
, but it doesn't really increase performances.
So my question is: what is the best way to make these divs move smoothly ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要求我提供一个提高速度的示例,我不是专家,但这就是我会做的:
不要将
setInterval
与字符串函数一起使用,它们必须运行 < code>eval 来运行,因此请使用它。事实上,我根本不会在主循环中使用setInterval
(参见第 #3 点)。存储您将多次使用的对象(尤其是在不断循环的函数中)。即使这个例子也不理想:
对于不断循环的函数,应尽可能简短并消除额外的函数调用。从你的第二个链接中,我压缩了这段代码:
进入这个更简洁的版本:
这仍然不理想,因为您的代码不断添加越来越多的对象。它应该受到限制,因为屏幕上有超过 200 个对象,并且页面变得缓慢。这也是为什么我会在最后一行使用
setTimeout
而不是您使用的setInterval
,因为脚本可能不会在您希望它执行之前循环遍历所有元素。重新开始。我确信其他人可以添加更多点来进一步优化我或您的代码:)
You asked me for an example to improve the speed, I'm not an expert but here is what I would do:
Don't use
setInterval
with string functions, they have to run througheval
to run, so use this instead. In fact I wouldn't usesetInterval
at all for the main loop (see point #3).Store an object you will be using multiple times (especially in a function that loops constantly). Even this example is not ideal:
For functions that loop constantly, be as short and concise as possible and eliminate extra function calls. From your second link, I compressed this code:
into this more concise version:
It's still not ideal, because your code keeps adding more and more objects. It should be limited because at one point I have over 200 objects on the screen and the page came to a crawl. This is also why I would use the
setTimeout
in the last line instead of thesetInterval
you use because the script may not have cycled through all of the elements before you want it to start again.I'm sure there are more points someone else could add to optimize my or your code even more :)