首页 > 解决方案 > 视差算法不适用于固定元素

问题描述

我已经编写了一个简单的视差插件,到目前为止它工作得非常好......translating当用户滚动页面时,它通过 X 轴(左右)和 Y 轴(上下)的指定元素工作.

到目前为止,我只position: fixed在 DOM 中的标准(非)项目上使用它。

但是,我现在尝试在具有fixed位置的元素内的元素上使用它,并且由于某种原因,我的算法正在0为每次翻译返回。我认为这与边界矩形有关,但我似乎无法解决。

这是算法:

let value = Math.round(((window_position + window_height - (height / 2) - (window_height / 2)) * item.options.speed) + (top * -1 * item.options.speed));

这是完整的脚本片段:

/**
 * Move each of the items based on their parallax
 * properties.
 *
 * @return void
 */
move() {

    let window_height   = window.innerHeight;
    let window_position = window.scrollY || window.pageYOffset;

    this.items.forEach((item) => {

        let { top, height } = item.element.getBoundingClientRect();

        // This will determine the exact position of the element in
        // the document
        top += window_position;

        // No need to proceed if the element is not in the viewport
        if ((top + height) < window_position || top > (window_position + window_height)) {
            return;
        }

        // Calculate the adjustment
        let value = Math.round(((window_position + window_height - (height / 2) - (window_height / 2)) * item.options.speed) + (top * -1 * item.options.speed));

        // Invert the adjustment for up and left directions
        if (['up', 'left'].includes(item.options.direction)) {
            value = -value;
        }

        // This returns 0, regardless of the window_position
        console.log(top, ((window_position + window_height - (height / 2) - (window_height / 2)) * item.options.speed), (top * -1 * item.options.speed));

        window.requestAnimationFrame(() => {

            // Do the CSS adjustment

        });

    });
}

标签: javascriptalgorithmmathparallax

解决方案


我采用了肮脏的修复方法(仍然接受建议):

// Calculate the adjustment
let value = (window_position + window_height - (height / 2) - (window_height / 2)) * item.options.speed;

// If the element is not fixed then adjust the algorithm
if (!item.options.fixed) {
    value += (top * -1 * item.options.speed);
}

value = Math.round(value);

推荐阅读