
本文介绍如何使用 jquery 动态计算滚动底部距离,为固定定位页脚(footer)创建平滑、响应式的渐显动画,使其随页面滚动自然浮现,与页眉淡出效果形成视觉呼应。
本文介绍如何使用 jquery 动态计算滚动底部距离,为固定定位页脚(footer)创建平滑、响应式的渐显动画,使其随页面滚动自然浮现,与页眉淡出效果形成视觉呼应。
在实现视差滚动或沉浸式长页面时,让页脚(
核心原理在于计算 scrollBottom(当前视口底部到文档底部的距离):
const scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
该值表示用户还需滚动多少像素才能抵达页面最底端。结合页脚自身高度(.outro.height()),即可线性映射为不透明度:
- scrollBottom ≤ 0 → 已到底部 → opacity = 1
- scrollBottom ≥ footerHeight → 远离底部 → opacity = 0
- 中间区间按比例插值:opacity = 1 - scrollBottom / footerHeight
完整实现代码如下:
$(document).ready(function() {
$(window).scroll(function() {
// 页眉淡出:随滚动向下,透明度递减
$(".intro").css("opacity", 1 - $(window).scrollTop() / $('.intro').height());
// 页脚淡入:随滚动接近底部,透明度递增
const scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
const footerHeight = $(".outro").height();
const opacity = Math.max(0, Math.min(1, 1 - scrollBottom / footerHeight));
$(".outro").css("opacity", opacity);
});
});
✅ 关键优化点:
- 使用 Math.max(0, Math.min(1, ...)) 确保 opacity 始终在 [0, 1] 区间内,避免负值或超限导致异常;
- 为 footer 添加 transition: opacity 75ms linear 实现流畅过渡,避免闪烁;
- CSS 中需确保 footer 为 position: fixed; bottom: 0;,且 z-index 低于内容容器以保证层叠逻辑正确。
HTML 结构与样式需严格配合:
- .intro(header)固定于顶部,.outro(footer)固定于底部;
- .container 内容区需预留足够 margin-bottom(至少等于 footer 高度),防止文字被遮挡;
- body { margin: 0; } 消除默认边距干扰布局精度。
此方案完全响应滚动位置,无需依赖节流(throttle)或 Intersection Observer,轻量可靠,适用于中低复杂度场景。如需更高性能或兼容原生 JS,可进一步封装为无依赖版本——但 jQuery 实现已兼顾可读性与实用性,是快速落地的理想选择。











