【发布时间】:2012-05-26 16:40:36
【问题描述】:
在以疯狂的速度创建多个 DIV 时,我试图找出有关性能的最佳做法。例如,在每个 .mousemove 事件上...
$('head').append("<style>.draw {width: 20px; height: 20px; position:fixed;</style>");
$(document).mousemove(function(mouseMOVE) {
//current mouse position
var mouseXcurrent = mouseMOVE.pageX;
var mouseYcurrent = mouseMOVE.pageY;
//function to create div
function mouseTRAIL(mouseX, mouseY, COLOR) {
$('body').append("<div class='draw' style='top:" + mouseY + "px; left:" + mouseX + "px; background: " + COLOR + ";'></div>");
}
// function call to create <div> at current mouse positiion
mouseTRAIL(mouseXcurrent, mouseYcurrent, '#00F');
// Remove <div>
setTimeout(function() {
$('.draw:first-child').remove();
}, 250);
});
所以,这一切都很好而且很花哨,但它的效率非常低(尤其是当我尝试填充每个鼠标移动位置之间的空间时)。这是一个例子......
$('head').append("<style>.draw {width: 20px; height: 20px; position:fixed;</style>");
$(document).mousemove(function(mouseMOVE) {
//current mouse position
var mouseXcurrent = mouseMOVE.pageX;
var mouseYcurrent = mouseMOVE.pageY;
// function to create div
function mouseTRAIL(mouseX, mouseY, COLOR) {
$('body').append("<div class='draw' style='top:" + mouseY + "px; left:" + mouseX + "px; background: " + COLOR + ";'></div>");
}
// function call to create <div> at current mouse positiion
mouseTRAIL(mouseXcurrent, mouseYcurrent, '#00F');
// variabls to calculate position between current and last mouse position
var num = ($('.draw').length) - 3;
var mouseXold = parseInt($('.draw:eq(' + num + ')').css('left'), 10);
var mouseYold = parseInt($('.draw:eq(' + num + ')').css('top'), 10);
var mouseXfill = (mouseXcurrent + mouseXold) / 2;
var mouseYfill = (mouseYcurrent + mouseYold) / 2;
// if first and last mouse postion exist, function call to create a div between them
if ($('.draw').length > 2) {
mouseTRAIL(mouseXfill, mouseYfill, '#F80');
}
// Remove <div>
setTimeout(function() {
$('.draw:first-child').remove();
$('.draw:nth-child(2)').remove();
}, 250);
});
我真的不知道如何改进。相信我,我尝试过研究,但效果不佳...我正在寻找的是一些建议、示例或指向更好实践的链接...
请注意,我正在自学编码。我是一名平面设计专业的学生,这就是我在课外度过暑假的方式......制作一些小项目来自学 JavasSript,有趣的东西 :)
我已经设置了一些 jsfiddles 来展示我在做什么...
Mouse Trail, More Elements - 非常非常慢
Mouse Trail, Less Elements - 非常慢
Mouse Trail, Bare Bones - 慢
【问题讨论】:
-
+1 表示一个非常有趣的项目。你应该把它做成一个 jQuery 插件!它也可以正常工作,Win7 上的 Chrome 19
-
什么很慢?它在我的 macbook 上运行良好
-
非常非常慢的运行对我来说就像一个魅力。我喜欢它。
-
乍一看,我只看到小东西。将
TRAILS定义移到外面(不需要一直重新定义),仅在需要时才计算值(如mouseXfill75)。如果它们真的被创建,请只调用remove()。但是这些不会给您带来很大的性能优势。顺便说一句,我在双核 Win7x64 上的 Chrome 上运行它,非常完美。 -
@Terry 另一个:运行
$('.draw').length两次效率低下。您应该查询 DOM 一次:var l = $('.draw').length;并使用l作为条件。更好的是:根本不要查询 DOM(这很“昂贵”)。维护一个变量,该变量将始终存储.draws 的当前数量。添加或删除一些时,更改变量。
标签: javascript jquery html performance function