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

新闻面板CSS Keyframe动画优化:解决初始显示问题与简化实现

问题解决方案

一、解决面板先显示最终位置的问题

你遇到的问题根源是元素默认样式就是动画的结束状态,动画启动前浏览器已经渲染了最终位置,触发动画时才切换到起始状态,所以会出现闪一下的情况。

解决思路:让元素默认处于动画的起始状态,动画执行时过渡到结束状态,同时通过animation-fill-mode: forwards确保动画结束后保持最终状态。另外,用transform: translateY()替代top/bottom实现位移,性能更好,不会触发页面重排。

二、简化重复的Keyframe代码

你现在每个盒子都写独立的keyframe和样式完全没必要,可通过以下方式大幅简化:

  • 提取所有盒子的公共样式到基础类
  • 只定义2个通用keyframes:控制从下方滑入、从上方滑入
  • 用额外类控制动画延迟、滑入方向等差异

修改后的完整代码

CSS

/* 所有新闻面板共享的基础样式 */
.news-box {
  width: auto;
  min-width: 185px;
  height: 300px;
  background-color: white;
  border: 1px solid black;
  border-radius: 8px;
  position: relative;
  padding: 10px;
  animation-duration: 2s;
  animation-fill-mode: forwards; /* 动画结束后保留最终状态 */
  opacity: 0; /* 默认透明,对应动画起始状态 */
}

/* 从下方滑入的通用动画 */
@keyframes slide-up {
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 从上方滑入的通用动画 */
@keyframes slide-down {
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 单个面板的差异配置 */
.box1 {
  left: 3em;
  transform: translateY(200px); /* 起始位置:下方200px */
  animation-name: slide-up;
}

.box2 {
  left: 4em;
  transform: translateY(-200px); /* 起始位置:上方200px */
  animation-name: slide-down;
  animation-delay: 1s;
}

.box3 {
  left: 5em;
  transform: translateY(200px);
  animation-name: slide-up;
  animation-delay: 2s;
}

.box4 {
  left: 6em;
  transform: translateY(200px);
  animation-name: slide-up;
  animation-delay: 3s;
}

HTML

<div class="about-section-two">
  <div class="row news-section" style="display: flex; padding: 4% 0; flex-direction: row; flex-wrap: wrap;">
    <div class="news-box box1">
      <h3>News header</h3>
      <p>lorum text</p>
    </div>
    <div class="news-box box2">
      <h3>News header</h3>
      <p>lorum text</p>
    </div>
    <div class="news-box box3">
      <h3>News header</h3>
      <p>lorum text</p>
    </div>
    <div class="news-box box4">
      <h3>News header</h3>
      <p>lorum text</p>
    </div>
  </div>
</div>

额外优化建议

  • 如果你用flex布局,完全可以去掉left属性,改用gap或margin控制面板间距,更符合flex布局逻辑
  • 可以用CSS变量统一控制位移距离、动画时长,比如:root { --slide-distance: 200px; --animation-duration: 2s; },后续修改更便捷

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:52:39