可重复使用的 CSS 变量视差效果

2025-06-07

可重复使用的 CSS 变量视差效果

CSS 变量为我们提供了一种在 CSS 和 JavaScript 之间共享信息的简洁方法。使用 CSS 变量连接两者的好处在于,我们可以随时在 CSS 和 JS 中访问和修改它们。

我以视差效果为例,但它的用途非常广泛。简而言之,视差效果是指网站背景滚动的速度比前景内容慢。让我们构建一个这样的效果,但要易于扩展。

我们将使用此卡作为示例。

牌

让我们首先处理 CSS 部分。

.card {
    --translate-y: 0px;
    --translate-x: 0px;
    transform: translate(var(--translate-x), var(--translate-y));

}
Enter fullscreen mode Exit fullscreen mode

因此,我们创建了两个 CSS 变量,分别用于水平和垂直移动,并将它们设置为所需的元素。接下来我们来学习 JavaScript。

创建函数

对于我们的函数,我们需要一些参数:元素要平移的方向(水平或垂直)、速度,以及要平移的值是否为负数

parallax = (element, direction, speed, negative) => {}
Enter fullscreen mode Exit fullscreen mode

需要平移的量取决于页面的滚动量。我们可以在窗口的 pageYOffset中访问这个量,但为了让页面看起来更平滑、更慢,我们需要稍微减少这个量,这时速度就派上用场了。这里也需要用到参数,并决定它是否为负数。

let translate = window.pageYOffset * speed * (negative ? -1 : 1);
Enter fullscreen mode Exit fullscreen mode

然后我们只需要将 CSS 变量更新为我们想要的方向和计算的数量。

element.style.setProperty(`--translate-${direction}`, `${translate}px`);
Enter fullscreen mode Exit fullscreen mode

但是如果我们还想同时在多个元素上使用此功能该怎么办?

parallax = (element, direction , speed , negative) => {
    let translate = window.pageYOffset * speed * (negative ? -1 : 1);

    if (element.length > 1) {
        element.forEach((el) => {
            el.style.setProperty(`--translate-${direction}`, `${translate}px`);
        });
    } else {
        element.style.setProperty(`--translate-${direction}`, `${translate}px`);
    }
};
Enter fullscreen mode Exit fullscreen mode

最后,我们只需要在页面滚动时监听并调用我们的函数。

const firstCard = document.querySelector('.cards-parallax .card');
const lastCard = document.querySelector('.cards-parallax .card:last-of-type');
const cards = document.querySelectorAll('.cards-parallax .card');
window.addEventListener('scroll', () => {
    parallax(firstCard,'y', 0.4, true);
    parallax(lastCard,'x', 0.5, false);
    parallax(cards,'x', 0.2, false);

});
Enter fullscreen mode Exit fullscreen mode

很酷的是,您可以对许多其他属性(如比例、旋转、不透明度甚至颜色等)采用相同的技术。

这是一个演示

文章来源:https://dev.to/sarmunbustillo/reusable-parallax-effect-with-css-variables-79d
PREV
我从 6 年的 CodeNewbie 构建过程中学到的东西 CodeNewbie 非常棒 - 我在技术领域建立的最重要的联系都是从社区开始的!
NEXT
Modern WebApps - Infrastructure: Vue, Parcel & Workbox