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

如何为动态数量的Box实现逐个依次CSS动画效果?

实现未知数量Box的逐个依次动画显示

当然可以实现,下面提供两种简单可行的方案,基于你现有的代码修改即可:

方案一:PHP渲染时直接添加动画延迟样式

利用PHP循环的索引值,给每个<li>元素设置递增的animation-delay,让每个Box的动画依次启动。

修改后的PHP代码:

<?php
if ($connexion) {
 // 执行查询
 $query = "SELECT * FROM asset_Services";
 $result = mysqli_query($connexion, $query);
 echo '<ul id="list">';
 // 根据查询结果输出列表项
 $index = 0;
  if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
      $br = (($index = ($index + 1) % 4) ? "" : "<br>");
      // 给每个li设置动画延迟,0.5秒间隔可自行调整
      $delay = $index * 0.5;
      echo '<li id="slider-'.$row["id"].'" style="animation-delay: '.$delay.'s;">
              <a href=""><h5 style="margin-top:20px">'.$row["nom"].'</h5></a>' . $br . 
            '</li>';
      $index++;
    }
  }
 echo '</ul>';
 // 关闭连接
}
?>

修正你的CSS小问题:

原CSS里opacity: 100是错误写法,应改为opacity: 1;同时初始透明度设为0才能看到淡入效果,建议加上animation-fill-mode: forwards确保动画结束后保持最终状态:

#list {
    margin: 2em auto;
    padding: 0;
    max-width: 70%;
    list-style: none;
    height: 100%;
}
#list a{
    color: #ccc;
}
#list h5 {
    color:#fff;
    margin-bottom:30px;
}
#list li {
    float: left;
    width: 250px;
    height: 100px;
    background: #012257;
    text-align: center;
    line-height: 20px;
    opacity: 0; /* 初始透明 */
    border-radius: 10px;
    margin-bottom:20px;
    margin-right:30px;
    animation: fadeIn 0.8s 1 ease-in forwards; /* 缩短动画时长更自然,可调整 */
}
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translate3d(0, -20%, 0);
    }
    to {
        opacity: 1;
        transform: translate3d(0, 0, 0);
    }
}

方案二:使用CSS变量+PHP动态赋值

这种方式把样式逻辑和PHP代码稍微分离,更易于维护:

PHP代码修改:

<?php
if ($connexion) {
 $query = "SELECT * FROM asset_Services";
 $result = mysqli_query($connexion, $query);
 echo '<ul id="list">';
 $index = 0;
  if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
      $br = (($index = ($index + 1) % 4) ? "" : "<br>");
      $delay = $index * 0.5;
      // 设置CSS变量--animation-delay
      echo '<li id="slider-'.$row["id"].'" style="--animation-delay: '.$delay.'s;">
              <a href=""><h5 style="margin-top:20px">'.$row["nom"].'</h5></a>' . $br . 
            '</li>';
      $index++;
    }
  }
 echo '</ul>';
}
?>

对应的CSS修改:

#list li {
    /* 其他样式保持不变 */
    opacity: 0;
    animation: fadeIn 0.8s 1 ease-in forwards;
    animation-delay: var(--animation-delay, 0s); /* 使用CSS变量,默认0秒 */
}

说明

  • 两种方案的核心都是给每个Box设置递增的动画延迟时间,延迟间隔(比如0.5秒)可以根据你的需求调整,数值越小,Box出现的间隔越短。
  • 原PHP中$index的递增逻辑存在混乱,已调整为每次循环后递增,确保索引正确对应每个Box的顺序。

内容的提问来源于stack exchange,提问作者Eiffel-mtl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:23:28