你好,StackOverflow社区,
我想实现的是一个可以用鼠标移动的标题。当你点击标题并拖动鼠标时,标题内的元素将以不同的速度移动。
我已经实现了视差效果,但性能并不是很好。在拖动背景时有点卡顿。
我的问题是:代码中可以做哪些改变来提高性能?
这是处理视差效果的代码部分。每次鼠标移动时,都会执行一个each循环,我认为这就是性能卡顿的原因:
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/ 提前感谢, Thomas
附言:也许有人能找出为什么第二层和第三层具有不同速度,但滚动速度相同的原因。