视差算法不适用于固定元素

Parallax Algorithm not working on Fixed Element

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

到目前为止,我只在 DOM.

中的标准(非 position: fixed)项目上使用它

但是,我现在正尝试在具有 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

        });

    });
}

我已经采用了一个肮脏的修复方法(仍然对建议持开放态度):

// 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);