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

滚动时文本距底部50px可见时切换图片的实现咨询

解决方案

要实现「当文本距屏幕底部约50px处变为可见时切换图片」的逻辑,我们需要调整滚动判断的触发条件——从监听元素顶部到达视口顶部,改为监听元素进入「视口底部往上50px」的触发区域。以下是修改后的完整代码和关键说明:

修改后的JavaScript代码

$(window).on("scroll touchmove", function() {
  // 计算关键位置:屏幕底部往上50px的水平线
  const scrollTop = $(document).scrollTop();
  const windowHeight = $(window).height();
  const triggerLine = scrollTop + windowHeight - 50;

  // 获取每个section的文档位置和总高度(包含内边距等)
  const oneTop = $("#one").offset().top;
  const oneBottom = oneTop + $("#one").outerHeight();
  const twoTop = $("#two").offset().top;
  const twoBottom = twoTop + $("#two").outerHeight();
  const threeTop = $("#three").offset().top;
  const threeBottom = threeTop + $("#three").outerHeight();
  const fourTop = $("#four").offset().top;
  const fourBottom = fourTop + $("#four").outerHeight();

  // 判断触发线落在哪个section范围内,切换对应图片
  if (triggerLine >= oneTop && triggerLine < oneBottom) {
    $('.image').css('background-image', 'url(https://i.postimg.cc/FRxNp6yG/hr-ax.png)');
  } else if (triggerLine >= twoTop && triggerLine < twoBottom) {
    $('.image').css('background-image', 'url(https://i.postimg.cc/wvz9hzm7/hr-bx.png)');
  } else if (triggerLine >= threeTop && triggerLine < threeBottom) {
    $('.image').css('background-image', 'url(https://i.postimg.cc/FRxNp6yG/hr-ax.png)');
  } else if (triggerLine >= fourTop) {
    $('.image').css('background-image', 'url(https://i.postimg.cc/wvz9hzm7/hr-bx.png)');
  }
});

关键修改点说明

  1. 新增触发线计算
    我们定义了triggerLine变量,它代表「屏幕底部往上50px」的位置,公式为:滚动距离 + 窗口高度 - 50,这是判断元素是否进入目标区域的核心参考线。

  2. 改用offset()获取元素位置
    原代码使用position().top获取的是元素相对于父元素的位置,容易受父元素定位影响;改用offset().top可以获取元素相对于文档顶部的绝对位置,判断更准确。

  3. 调整判断逻辑
    原逻辑判断「滚动顶部是否到达元素顶部区间」,现在改为判断「触发线是否落在当前section的垂直范围内」——当triggerLine进入某个section的顶部到底部区间时,就切换对应图片,完美匹配「文本距底部50px可见时切换」的需求。

  4. 优化条件结构
    将多个独立if改为else if,避免每次滚动都执行所有判断,提升代码执行效率。

可选性能优化:防抖处理

滚动事件会频繁触发,添加防抖函数可以减少不必要的计算,提升页面流畅度:

// 防抖函数:延迟执行回调,避免频繁触发
function debounce(func, delay = 100) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(func, delay);
  };
}

// 绑定带防抖的滚动事件
$(window).on("scroll touchmove", debounce(function() {
  // 此处放入上面的核心判断代码
}));

内容的提问来源于stack exchange,提问作者Elaine Byene

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:10:57