如何修改jQuery滚动监听代码 实现滚动80vh后调整图片透明度
调整后代码
$(window).scroll(function() { const scrollTop = $(this).scrollTop(); // 计算80vh对应的像素阈值 const triggerThreshold = $(window).height() * 0.8; $('.image123').css({ opacity: function() { const elementHeight = $(this).height(); // 滚动未达到阈值时保持完全不透明 if (scrollTop < triggerThreshold) { return 1; } // 超过阈值后计算渐变透明度,限制最小值为0 const opacity = (elementHeight - (scrollTop - triggerThreshold)) / elementHeight; return Math.max(0, opacity); } }); });
改动说明
- 新增
triggerThreshold变量,通过窗口高度乘以0.8得到80vh对应的实际像素值,作为触发透明度变化的临界点 - 增加滚动距离判断逻辑:滚动距离小于80vh时,元素透明度固定为1,保持完全显示状态
- 调整透明度计算逻辑,以超过80vh的滚动距离作为计算基准,保证渐变效果从80vh的位置才开始触发
- 新增
Math.max(0, opacity)边界处理,避免透明度出现负值导致样式异常
如果需要兼容窗口缩放场景,可以额外增加resize事件监听实时更新阈值:
let triggerThreshold = $(window).height() * 0.8; // 窗口大小变化时更新阈值 $(window).resize(() => { triggerThreshold = $(window).height() * 0.8; }); $(window).scroll(function() { const scrollTop = $(this).scrollTop(); $('.image123').css({ opacity: function() { const elementHeight = $(this).height(); if (scrollTop < triggerThreshold) return 1; const opacity = (elementHeight - (scrollTop - triggerThreshold)) / elementHeight; return Math.max(0, opacity); } }); });
内容的提问来源于stack exchange,提问作者crapatjquery
相关产品推荐
相关产品推荐

