CSS动画问题:如何实现图片上滑过程中逐步显示的效果?
解决方案
你需要的效果只需要修改少量CSS即可实现,核心是给父容器增加定位和溢出隐藏规则:
- 给容纳僵尸、背景、前景泥土的
td元素添加position: relative属性,这样内部绝对定位的元素会以该td为基准定位,不再脱离当前容器的控制 - 给同一个
td添加overflow: hidden,超出该容器范围的内容会被自动剪裁隐藏,正好实现僵尸藏在泥土下、弹出时逐步显示的效果 - 微调僵尸和前景泥土的定位值,适配父容器的基准定位,避免错位
修改后完整代码:
/* 给父td添加的样式,你可以给这个td加个类比如.game-cell来应用 */ td { position: relative; overflow: hidden; width: 220px; height: 140px; padding: 0; } .background { width: 220px; z-index: 5; display: block; } .frontdirt { width: 220px; position: absolute; left: 0; top: 0; z-index: 15; } .zombie { animation: popup 2s ease-in-out 10 forwards; position: absolute; width: 220px; top: 100%; /* 初始完全藏在容器下方 */ left: 0; z-index: 10; } @keyframes popup { 0% { transform: translateY(0px); } 50% { transform: translateY(-100%); } 100% { transform: translateY(0px); } }
<table> <tr> <td> <img src="https://www.codeeverydamnday.com/images/beforezombie2.png" class="background" alt="背景" /> <img src="https://www.codeeverydamnday.com/images/zombie.png" class="zombie" alt="僵尸" /> <img src="https://www.codeeverydamnday.com/images/groundfront2.png" class="frontdirt" alt="前景泥土" /> </td> </tr> <tr> <td> <img src="https://www.codeeverydamnday.com/images/beforezombie2.png" class="background" alt="背景" /> </td> </tr> </table>
可选替代思路(无需absolute定位)
如果你不想用绝对定位,可以用Grid布局实现图层堆叠:给父td设置display: grid,三个子元素默认都会堆叠在同一个网格区域,不需要定位也能实现层级叠放,z-index规则依然生效,配合overflow: hidden也能实现相同的剪裁效果。
内容的提问来源于stack exchange,提问作者Katie Reynolds
相关产品推荐
相关产品推荐

