使用jQuery mousemove实现视差背景时,窗口缩放背景图被裁切如何修复?
修复视差背景窗口Resize后裁切的问题
嘿,这个问题我之前也碰到过!窗口 resize 后背景裁切,核心原因有两个:一是你的尺寸计算逻辑只在鼠标移动时执行,窗口大小改变后,.landing的宽高已经变化但没有重新计算,导致视差偏移的基准还是旧数据;二是背景元素的 CSS 配置没跟上自适应需求,容易出现裁切。下面是具体的修复方案:
1. 重构尺寸计算逻辑,绑定Resize事件
把容器尺寸的计算抽成独立函数,在页面初始化、鼠标移动、窗口 resize 时都调用,保证始终使用最新的尺寸数据:
// 全局变量存储最新的容器半宽高 let halfLandingWidth = 0; let halfLandingHeight = 0; // 计算并更新容器尺寸的函数 function updateLandingDimensions() { const $landing = $('.landing'); halfLandingWidth = $landing.width() / 2; halfLandingHeight = $landing.height() / 2; } $(document).ready(function() { // 页面加载时先初始化尺寸 updateLandingDimensions(); // 鼠标移动时用最新尺寸计算视差偏移 $('.landing').mousemove(function(e){ // 获取鼠标在容器内的相对坐标 const mouseX = e.pageX - $(this).offset().left; const mouseY = e.pageY - $(this).offset().top; // 计算偏移量(最后的20是视差系数,可根据需求调整) const moveX = (mouseX - halfLandingWidth) / 20; const moveY = (mouseY - halfLandingHeight) / 20; // 给不同层级的背景设置反向/正向偏移,实现视差 $('.shapes1').css('transform', `translate(${moveX}px, ${moveY}px)`); $('.shapes2').css('transform', `translate(${-moveX}px, ${-moveY}px)`); }); // 窗口resize时更新尺寸,用防抖避免频繁触发 $(window).on('resize', debounce(function() { updateLandingDimensions(); }, 250)); }); // 防抖函数,优化resize事件的性能 function debounce(func, delay) { let timer; return function() { clearTimeout(timer); timer = setTimeout(func, delay); }; }
2. 优化背景元素的CSS配置
确保背景图在任何窗口尺寸下都能自适应,避免裁切:
.landing { position: relative; width: 100vw; height: 100vh; overflow: hidden; /* 防止背景元素偏移后超出容器出现滚动条 */ } .shapes { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-size: cover; /* 保证背景图覆盖整个元素,比例不变形 */ background-position: center center; /* 背景图始终居中,裁切时保留核心区域 */ } .shapes1 { background-image: url('你的背景图1路径'); } .shapes2 { background-image: url('你的背景图2路径'); }
修复原理说明
- 抽离
updateLandingDimensions函数后,每次窗口大小改变都会重新计算容器的半宽高,确保视差偏移的基准始终是最新的,不会出现错位。 - 防抖函数
debounce可以避免resize事件频繁触发,减少不必要的计算,提升页面性能。 - CSS里的
background-size: cover和background-position: center,保证背景图在任何尺寸下都能居中覆盖元素,即使有裁切也会保留核心区域;.landing的overflow: hidden可以防止背景元素偏移后超出容器出现滚动条。
内容的提问来源于stack exchange,提问作者AlwaysStudent
相关产品推荐
相关产品推荐

