js实现视差效果
使用CSS和JavaScript实现视差效果
视差效果可以通过CSS的background-attachment: fixed或JavaScript动态调整元素位置来实现。以下是两种常见方法:
CSS视差(简单静态效果)
通过CSS的background-attachment属性实现静态视差背景:
.parallax-section {
background-image: url("image.jpg");
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
}
JavaScript动态视差(更灵活)
通过监听滚动事件动态计算元素位移:
window.addEventListener('scroll', function() {
const parallaxElements = document.querySelectorAll('.parallax');
const scrollPosition = window.pageYOffset;
parallaxElements.forEach(element => {
const speed = parseFloat(element.dataset.speed) || 0.5;
const offset = scrollPosition * speed;
element.style.transform = `translateY(${offset}px)`;
});
});
对应HTML结构:

<div class="parallax" data-speed="0.5"></div>
性能优化方案
使用requestAnimationFrame优化滚动性能:
let ticking = false;
window.addEventListener('scroll', function() {
if (!ticking) {
window.requestAnimationFrame(function() {
updateParallax();
ticking = false;
});
ticking = true;
}
});
function updateParallax() {
const scrollTop = window.pageYOffset;
document.querySelector('.parallax').style.transform =
`translateY(${scrollTop * 0.3}px)`;
}
现代CSS视差(CSS perspective)
使用CSS 3D变换创建层次感:

.parallax-container {
perspective: 1px;
height: 100vh;
overflow-x: hidden;
overflow-y: auto;
}
.parallax-layer {
position: absolute;
transform: translateZ(var(--depth));
}
JavaScript设置深度:
document.querySelector('.layer-1').style.setProperty('--depth', '-0.5px');
视差库推荐
-
Rellax.js - 轻量级视差库(仅3KB)
new Rellax('.parallax-element', { speed: -2, center: true }); -
Parallax.js - 支持鼠标移动交互
var scene = document.getElementById('scene'); var parallax = new Parallax(scene);
注意事项
- 移动端需谨慎使用视差效果,可能影响性能
- 考虑添加
will-change: transform提升渲染性能 - 对于复杂场景建议使用WebGL方案(如Three.js)
以上方法可根据项目需求组合使用,CSS方案适合简单场景,JavaScript方案提供更精细的控制能力。






