在以疯狂的速度创建多个 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 来展示我在做什么......
鼠标轨迹,更多元素- 非常非常慢
鼠标轨迹,更少元素- 非常慢
鼠标轨迹,Bare Bones - 慢