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

标签 javascript algorithm math parallax

我写了一个简单的视差插件,到目前为止效果非常好......它通过 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);

关于javascript - 视差算法不适用于固定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56568581/

相关文章:

javascript - excel可以根据网站的变量填写某些字段吗?

algorithm - 计算时间序列中的周期

c# - 20 位整数数学

javascript - 使用 Express 和 MongoDB - 如何注销用户?

javascript - 我的 jquery 切换出了什么问题

javascript - 使用 jQuery 或 JavaScript 从 Select 下拉数组中选择或获取所有值

c++ - 计算字符串中元音的函数

facebook - TOH 输入格式说明

objective-c - 沿着 CGPathRef 寻找中间点

math - 数学与编程语言的融合