如何实现带视差(Parallax)效果的图片文字背景
文字背景图视差效果实现方案
先修正你现有代码的问题
你原代码的核心问题是监听了滚轮事件,但错误使用了鼠标坐标来计算背景偏移,滚轮事件应该基于滚动的偏移量来调整,而不是鼠标位置。另外背景图尺寸太小,导致视差效果不明显。
修改后的可运行代码:
JS 代码
let currentX = 40; // 初始背景X偏移百分比 let currentY = 50; // 初始背景Y偏移百分比 document.addEventListener("wheel", e => { // 按滚动方向调整偏移,数值越大视差越强 currentX += e.deltaY * 0.05; currentY += e.deltaY * 0.03; // 限制偏移范围,防止背景完全移出文字区域 currentX = Math.max(0, Math.min(100, currentX)); currentY = Math.max(0, Math.min(100, currentY)); document.querySelector(".title").style.backgroundPosition = `${currentX}% ${currentY}%`; });
CSS 关键修改
.title { background: url("https://images.unsplash.com/photo-1470813740244-df37b8c1edcb?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=2b76b1e6da83c1a0f59eebaa481e12aa&auto=format&fit=crop&w=751&q=80") center no-repeat; background-position: 40% 50%; background-size: 150%; /* 放大背景图,让视差移动更直观 */ -webkit-background-clip: text; background-clip: text; /* 补全标准属性,兼容更多浏览器 */ color: transparent; /* 保留你原有的其他样式 */ }
更优的两种实现方向
1. JS 驱动方案(推荐,灵活可控)
适合需要复杂交互(比如鼠标移动+滚轮双触发视差)的场景,核心是监听对应事件,动态调整背景位置或元素变换:
如果要做鼠标移动触发的视差(原代码可能的初衷),替换事件监听为mousemove:
const title = document.querySelector(".title"); const winWidth = window.innerWidth; const winHeight = window.innerHeight; document.addEventListener("mousemove", e => { // 计算鼠标在窗口中的占比,转换为背景偏移量,数值越小视差越柔和 const xOffset = (e.clientX / winWidth) * 20; const yOffset = (e.clientY / winHeight) * 20; title.style.backgroundPosition = `${40 - xOffset}% ${50 - yOffset}%`; });
2. CSS 驱动方案(简洁,纯滚动视差)
不需要JS,利用background-attachment: fixed实现纯CSS视差,适合简单场景:
.title { background: url("你的图片地址") center fixed no-repeat; background-size: 120%; -webkit-background-clip: text; background-clip: text; color: transparent; /* 其他样式保留 */ }
页面滚动时,背景图固定不动,文字随页面滚动,自然形成视差。缺点是无法自定义偏移强度,灵活性有限。
实用技巧与注意事项
- 背景图尺寸必须放大:设置
background-size为120%-200%,如果和文字尺寸一致,移动时看不到视差效果。 - 兼容性处理:
background-clip: text在现代浏览器都支持,Safari需加-webkit-前缀。如果要兼容旧浏览器,用伪元素+clip-path模拟:
然后JS修改伪元素的.title { position: relative; color: transparent; } .title::before { content: attr(data-text); position: absolute; top: 0; left: 0; background: url("你的图片地址") center no-repeat; background-size: 150%; -webkit-background-clip: text; background-clip: text; color: transparent; z-index: -1; transition: transform 0.1s ease; }transform: translate()来实现视差,性能比直接改background-position更好。 - 性能优化:频繁修改
background-position会触发重绘,优先用transform(配合伪元素方案),因为transform仅触发复合层更新,性能更高。
内容的提问来源于stack exchange,提问作者Mahesh Thorat
相关产品推荐
相关产品推荐

