javascript - 视差算法不适用于固定元素
问题描述
我已经编写了一个简单的视差插件,到目前为止它工作得非常好......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
});
});
}
解决方案
我采用了肮脏的修复方法(仍然接受建议):
// 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);
推荐阅读
- algorithm - 当这两个元素相等/不相等时:最接近平均值的元素与中位数?
- python - 替换 Numpy 数组的一部分时避免不正确的舍入
- c++ - 宿舍访问问题(优先队列申请)
- list - 我在 2013 年创建了一个带有到期日期和电子邮件 ID 的 Sharepoint 列表。要求是必须生成自动邮件
- javascript - 纱线链接适用于一个文件,但在同一个 Angular 项目中为另一个文件抛出错误
- laravel - laravel中的循环问题
- php - 不要使用 Google Translate API 翻译双花括号之间的数据
- node.js - 角度服务器端构建错误无法找到错误
- c# - 使用 System.Text.Json 使用动态键查询或反序列化 json
- tableau-api - Tableau中如何使用excel的averageif函数