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

页面加载时背景高度从0到100%逐帧增长的实现方案

嘿,别纠结啦,你想要的这个背景高度逐步增长的效果其实不难实现,我给你准备了几个不同的方案,按需挑选就行~

方案1:纯CSS关键帧动画(首推,无需JS)

这个方案最省心,完全靠浏览器原生的CSS动画实现,不需要额外脚本,性能还特别好。刚好能满足你“10秒内从0到100%,每秒增长10%”的线性需求。

先给页面和背景容器设置基础样式,确保高度计算正确:

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden; /* 避免动画过程中出现滚动条 */
}

.bg-loader {
  position: fixed; /* 固定在视口,覆盖整个页面 */
  top: 0;
  left: 0;
  width: 100%;
  height: 0; /* 初始高度为0 */
  background-color: #2c3e50; /* 换成你自己需要的背景色 */
  animation: growHeight 10s linear forwards; /* 10秒线性动画,结束后保持最终状态 */
}

/* 定义高度增长的关键帧 */
@keyframes growHeight {
  from {
    height: 0;
  }
  to {
    height: 100%;
  }
}

然后在HTML里添加这个背景元素就行:

<div class="bg-loader"></div>
<!-- 你的页面内容放在这个元素后面就行 -->
方案2:jQuery实现(适合已用jQuery的项目)

如果你的项目已经引入了jQuery,用JS控制的话灵活性更高,比如你可以轻松添加动画结束后的回调逻辑。

HTML结构和上面一样,先写基础CSS:

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.bg-loader {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 0;
  background-color: #2c3e50;
}

然后写jQuery代码:

$(document).ready(function() {
  const totalTime = 10000; // 总时长10秒(毫秒)
  const updateInterval = 1000; // 每秒更新一次高度
  const heightStep = 10; // 每次增长10%
  let currentHeight = 0;

  const heightTimer = setInterval(function() {
    currentHeight += heightStep;
    $('.bg-loader').css('height', currentHeight + '%');
    
    // 高度达到100%时停止定时器
    if (currentHeight >= 100) {
      clearInterval(heightTimer);
      // 这里可以加动画结束后的操作,比如恢复页面滚动
      // $('body').css('overflow', 'auto');
    }
  }, updateInterval);
});
方案3:原生JavaScript实现(无任何依赖)

不想用库的话,原生JS也能轻松搞定,逻辑和jQuery版本一致,只是写法更原生:

HTML和CSS和上面保持一致,JS代码如下:

window.addEventListener('load', function() {
  const bgElement = document.querySelector('.bg-loader');
  const totalTime = 10000;
  const updateInterval = 1000;
  const heightStep = 10;
  let currentHeight = 0;

  const heightTimer = setInterval(() => {
    currentHeight += heightStep;
    bgElement.style.height = `${currentHeight}%`;

    if (currentHeight >= 100) {
      clearInterval(heightTimer);
      // 动画结束后可以添加自定义逻辑
    }
  }, updateInterval);
});

小提醒

  • 如果背景元素会挡住页面内容,记得给内容容器设置position: relative或者合适的z-index值。
  • 纯CSS方案是连续平滑的动画,视觉效果比每秒跳一次的JS方案更自然;如果一定要严格“每秒跳10%”,那JS方案更精准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:26:33