你好 StackOverflow 社区,
我想要实现的是一个可以用鼠标移动的标题。您单击标题并拖动鼠标,标题内的元素将以不同的速度移动。
我实现了视差部分,但性能并不是很好。拖动背景时,它部分有点滞后。
我现在的问题是:可以在代码中进行哪些更改以提高性能?
这是处理视差的代码部分。在每个 mousemove 上执行每个循环,我认为这是性能如此滞后的原因:
var dragging = false;
var clickMouseX;
//Our object for the layers
//each layer has a different scrolling speed
var movingObjects = {
'#header-l1' : {'speed': 1},
'#header-l2' : {'speed': 1.4},
'#header-l3' : {'speed': 1.85},
'#header-l4' : {'speed': 2.2},
};
$('#header-wrapper').mousedown(function(e){
dragging = true;
//Get initial mouse position when clicked
clickMouseX = e.pageX;
$(this).mousemove(function(mme){
//execute only if mousedown
if(dragging){
//iterate through all layers which have to be parallaxed
$.each(movingObjects, function(el, opt){
var element = $(el);
//get difference of initial mouse position and current mouse position
var diff = clickMouseX - mme.pageX;
//scroll-position left speed 1
if(diff < 0) diff = -1;
//scroll position right speed 1
if(diff >= 0) diff = 1;
//get current position of layer
currLeft = parseInt(element.css('left'));
//get current layer width
elWidth = element.width();
//if right border is reached don't scroll further
if(currLeft < -(elWidth - 810)){
element.css('left', -(elWidth - 810));
}
//so do with left border
if(currLeft > 0){
element.css('left', 0);
}
//parallax it! Subtract the scroll position speed multiplied by the speed of the desired
//layer from the current left property
element.css('left', parseInt(element.css('left')) - diff*opt.speed);
});
}
});
/* Cursor */
$(this).css('cursor', 'pointer');
return false;
});
我也提琴了:http: //jsfiddle.net/yWGDz/
在此先感谢,托马斯
PS也许有人甚至会发现为什么第二层和第三层具有相同的滚动速度而定义了不同的速度。