视觉差(Parallax)效果在网页设计中常被用来增加页面的深度感和动态视觉体验。通过视觉差效果,当用户滚动页面时,不同层次的元素会以不同的速度移动,从而模拟出三维空间中的深度感。
z-index
来控制堆叠顺序。background-attachment: fixed
或 background-position
属性,使其在滚动时保持固定或相对移动。transform
属性(如 translateY
)来实现移动效果。<div class="parallax-container">
<div class="parallax-layer background"></div>
<div class="parallax-layer midground"></div>
<div class="parallax-layer foreground"></div>
</div>
.parallax-container {
height: 100vh;
overflow-x: hidden;
overflow-y: auto;
perspective: 1px;
}
.parallax-layer {
position: absolute;
width: 100%;
height: 100vh;
}
.background {
background-image: url('background.jpg');
background-size: cover;
transform: translateZ(-1px) scale(2);
}
.midground {
background-image: url('midground.png');
transform: translateZ(-0.5px) scale(1.5);
}
.foreground {
background-image: url('foreground.png');
}
window.addEventListener('scroll', function() {
const scrollPosition = window.pageYOffset;
const background = document.querySelector('.background');
const midground = document.querySelector('.midground');
const foreground = document.querySelector('.foreground');
background.style.transform = `translateY(${scrollPosition * 0.5}px)`;
midground.style.transform = `translateY(${scrollPosition * 0.75}px)`;
foreground.style.transform = `translateY(${scrollPosition}px)`;
});
requestAnimationFrame
优化滚动事件的处理,减少不必要的 DOM 操作。transform
和 perspective
属性的支持可能不同。z-index
和 transform
属性,确保元素按预期排列。通过以上方法,可以实现一个流畅且具有深度感的视觉差效果。
领取专属 10元无门槛券
手把手带您无忧上云