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

如何设置网站Footer仅在滚动至页面底部时显示?

滚动到底部才显示Footer的实现方案

核心思路

默认把Footer藏起来,通过JS监听滚动事件,判断用户滚到页面底部时再显示它,同时用CSS过渡做个平滑的显示效果,避免突兀。

具体实现步骤

1. 调整Footer的CSS样式

先去掉fixed定位,改用absolute(不占页面空间,不影响原有布局),默认设置隐藏状态:

footer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  /* 初始隐藏 */
  opacity: 0;
  visibility: hidden;
  /* 平滑过渡效果 */
  transition: opacity 0.3s ease, visibility 0.3s ease;
  /* 保留你的原有样式 */
  background-color: #fff;
  padding: 1.5rem;
}

/* 控制显示的类 */
footer.show-footer {
  opacity: 1;
  visibility: visible;
}

2. 给页面容器加基础样式

为了让Footer的absolute定位生效,给body加相对定位和最小高度,同时预留Footer高度的内边距,防止底部内容被Footer遮挡:

body {
  position: relative;
  min-height: 100vh;
  margin: 0;
  /* 这里的数值要和Footer的高度一致 */
  padding-bottom: 90px;
}

3. 添加JavaScript监听逻辑

监听滚动事件,计算当前滚动位置是否到达页面底部,满足条件就给Footer加显示类:

// 监听滚动事件
window.addEventListener('scroll', checkScrollPosition);

// 页面加载时先检查一次,避免内容太短时Footer不显示
window.addEventListener('load', checkScrollPosition);

function checkScrollPosition() {
  const footer = document.querySelector('footer');
  // 页面总高度
  const totalPageHeight = document.documentElement.scrollHeight;
  // 当前滚动位置 + 视口高度
  const currentScroll = window.scrollY + window.innerHeight;
  // 加20px容错,避免计算误差导致不触发
  const tolerance = 20;

  if (currentScroll >= totalPageHeight - tolerance) {
    footer.classList.add('show-footer');
  } else {
    footer.classList.remove('show-footer');
  }
}

为什么之前的定位方式没效果?

  • sticky定位是滚动到指定位置固定在视口,无法实现“只在底部显示”的逻辑;
  • relative定位会占据页面空间,默认就会显示在内容下方,不符合需求;
  • fixed定位直接固定在视口,会一直显示,和你的需求完全相反。

内容的提问来源于stack exchange,提问作者cjdjdude _

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 03:49:58