为什么我的图像在执行这个视差脚本时跳了几个像素

Why does my images jump a few pixels when executing this parallax script?

本文关键字:像素 几个 脚本 图像 我的 执行 视差 为什么      更新时间:2023-09-26

我不是javascript的家伙,所以我真的不明白为什么我的代码这样做:

当第一次加载页面并滚动时,目标图像向上下移约30px

var parallax = document.querySelectorAll(".headerphotosmall, .headerphoto"),
    speed = 0.9;
window.onscroll = function(){
    [].slice.call(parallax).forEach(function(el,i){
        var windowYOffset = window.pageYOffset,
            elBackgrounPos = "50%" + (windowYOffset * speed) + "px";
        el.style.backgroundPosition = elBackgrounPos;
    });
};

视频显示我的问题:https://i.gyazo.com/040f328ac78a5d5243e37352e19e0cf6.mp4

我认为@BeyelerStudios的评论解释了这个问题…图像的初始位置与初始滚动位置无关。

我不知道什么是视差,虽然…

因为我不知道你的CSS,我试图自动更新你的视差图像的位置时,脚本运行,与Array#forEach循环。如果稍后声明这些背景图像,则需要等待页面加载。

var parallax, speed;
var updateBgImagePos, updateParallaxPosition;
// Converts parallax HTML collection to
// Array
parallax = [].slice.call(
    document.querySelectorAll(".headerphotosmall, .headerphoto")
);
speed = 0.9;
updateBgImagePos = function(el, i) {
    var windowYOffset = window.pageYOffset,
        elBackgrounPos = "50%" + (windowYOffset * speed) + "px";
    el.style.backgroundPosition = elBackgrounPos;
};
updateParallaxPosition = function() {
    parallax.forEach(updateBgImagePos);
};
window.onscroll = updateParallaxPosition;
// If your script is declared later than the images,
// you don't need to wait the page to load  to
// get/modify them.
updateParallaxPosition();