You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用smooth-parallax实现Y轴视差滚动?解决X轴偏移问题

视差滚动Y轴移动问题解决

我想实现某网站顶部的视差滚动效果,目前使用smooth-parallax库,但图片始终沿X轴左右移动,无法实现Y轴上下滚动的效果,求帮助。

我的图片代码

<img src="https://res.cloudinary.com/find-my-man-and-van/image/upload/c_scale,q_50,w_1600/v1653118079/parallax/clouds.webp" alt="clouds" smooth-parallax end-position-y="0.15" id="sky">
<img src="https://res.cloudinary.com/find-my-man-and-van/image/upload/c_scale,q_auto:good,w_800/v1652954804/parallax/bground-layer-4-01.webp" alt="mountains" smooth-parallax end-position-y="0.05"
     id="mountainsLayer">
<img src="https://res.cloudinary.com/find-my-man-and-van/image/upload/c_scale,q_auto:good,w_1000/v1652954804/parallax/bground-layer-3-01.webp" alt="city" smooth-parallax end-position-y="0.25"
     id="backLayer">

初始化代码

window.addEventListener("load", function () {
SmoothParallax.init();
});

问题排查与解决

根据smooth-parallax库的特性,默认可能同时启用了X轴和Y轴视差,你需要明确禁用X轴滚动,确保仅触发Y轴效果:

  1. 给图片添加disable-x属性
    在每个带有smooth-parallax属性的img标签中加入disable-x="true",强制关闭X轴方向的偏移:
<img src="https://res.cloudinary.com/find-my-man-and-van/image/upload/c_scale,q_50,w_1600/v1653118079/parallax/clouds.webp" alt="clouds" smooth-parallax end-position-y="0.15" disable-x="true" id="sky">
<img src="https://res.cloudinary.com/find-my-man-and-van/image/upload/c_scale,q_auto:good,w_800/v1652954804/parallax/bground-layer-4-01.webp" alt="mountains" smooth-parallax end-position-y="0.05" disable-x="true"
     id="mountainsLayer">
<img src="https://res.cloudinary.com/find-my-man-and-van/image/upload/c_scale,q_auto:good,w_1000/v1652954804/parallax/bground-layer-3-01.webp" alt="city" smooth-parallax end-position-y="0.25" disable-x="true"
     id="backLayer">
  1. 确保容器样式正确
    视差效果需要基于容器的滚动高度计算偏移,给图片的父容器添加必要的定位和高度样式:
.parallax-wrapper {
  position: relative;
  height: 600px; /* 根据页面需求调整高度 */
  overflow: hidden;
}
.parallax-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: auto;
}
  1. 全局初始化配置(可选)
    如果单标签属性不生效,可以在初始化时全局禁用X轴:
window.addEventListener("load", function () {
  SmoothParallax.init({
    disableX: true
  });
});

完成以上修改后,图片应该会随页面滚动沿Y轴上下移动,实现目标视差效果。


内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:40:32