我已创建此功能,以视差滚动传递的元素的背景图像。
当下面的示例中,当视口高度小于600px(彩虹图像的高度为600px)时,彩虹背景不能正确覆盖其背后的灰色元素(它应始终完全覆盖) ,但滚动得太快了)
我似乎无法弄明白我需要的额外条款。你能帮我指点一个方程式来动态地偏移背景吗?
jsfiddle重新创建:http://jsfiddle.net/3htbj/
/**
Get the height of the passed element's background image.
@param {element} element - An element.
@returns {int} The height of the background.
***************************************************************************/
function getBackgroundHeight(element){
return 600;
}
/**
Parallax scroll the passed element's background relative to the element.
@param {element} element - An element.
***************************************************************************/
function parallaxScrollElement(element){
var hV=window.innerHeight;
var hE=element.clientHeight;
var hB=getBackgroundHeight(element);
var yV=window.pageYOffset; //Relative to document.
var yE=element.getBoundingClientRect().top; //Relative to view-port.
var yB=((hB-hE)*yE)/(hE-hV); //Relative to element.
element.style.backgroundPositionY=yB+"px";
}
/**
Parallax scroll all elements with CSS class 'parallax'. This function
should be called onScroll.
***************************************************************************/
function parallaxScroll(){
var parallaxScrollElements=document.getElementsByClassName("parallax");
for(var i=0;i<parallaxScrollElements.length;i++)
parallaxScrollElement(parallaxScrollElements[i]);
};
window.onscroll=function(){
parallaxScroll();
}
window.onresize=function(){
parallaxScroll();
}
答案 0 :(得分:2)
如果您希望将视差滚动与页面内容一起使用,请尝试:
var yB=((yE)/(hV))*(hE-hB);
答案 1 :(得分:1)
如果有兴趣的话,我有以下工作:
var yB=(1-((yE+hE)/(hV + hE)))*(hE-hB); //Relative to element.