You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:57:03