视差背景滚动方程-包括示例

Parallax Background Scroll Equation - Example Included

本文关键字:-包 方程 背景 滚动 视差      更新时间:2023-09-26

我创建了这个函数来视差滚动传递元素的背景图像。

  • 当视口的高度大于或等于背景图像的高度时,该功能工作良好。
  • 但是,当视口的高度小于背景图像的高度时,图像滚动得太快。

当viewport的高度小于600px (600px是下图中彩虹图像的高度)时,彩虹背景没有正确地覆盖它后面的灰色元素(它应该一直被完全覆盖,但是滚动得太快了)

我似乎不能算出yB中需要的额外项。你能帮我指出一个方程的正确方向来动态地抵消背景吗?

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();
}

如果你正在寻找视差滚动随着页面的内容,尝试:

var yB=((yE)/(hV))*(hE-hB);

如果有人感兴趣,我得到了以下工作:

    var yB=(1-((yE+hE)/(hV + hE)))*(hE-hB); //Relative to element.