如何使用CSS Animation实现符合规则的H1文本自动动态替换?
用CSS动画实现H1标题内容自动切换
实现思路
在H1标签内嵌套对应不同状态的文本节点,通过CSS关键帧动画控制每个节点的显示与隐藏,实现每4秒自动切换一组符合规则的文本内容,全程无需JavaScript。
HTML结构
<h1 class="rotating-title"> <span>If I'm CAT, then I'm not a DOG or ELEPHANT.</span> <span>If I'm DOG, then I'm not CAT or ELEPHANT.</span> <span>If I'm ELEPHANT, then I'm not CAT or DOG.</span> <span>If I'm HIPPO, then I'm not ELEPHANT or LION.</span> <span>If I'm LION, then I'm not ELEPHANT or HIPPO.</span> </h1>
CSS样式
/* 固定标题高度,避免切换时页面跳动 */ .rotating-title { height: 1.5em; overflow: hidden; position: relative; } /* 初始化所有文本节点为隐藏状态 */ .rotating-title span { position: absolute; top: 0; left: 0; width: 100%; opacity: 0; visibility: hidden; animation: rotateText 20s infinite; } /* 为每个文本节点设置动画延迟,实现依次显示 */ .rotating-title span:nth-child(1) { animation-delay: 0s; } .rotating-title span:nth-child(2) { animation-delay: 4s; } .rotating-title span:nth-child(3) { animation-delay: 8s; } .rotating-title span:nth-child(4) { animation-delay: 12s; } .rotating-title span:nth-child(5) { animation-delay: 16s; } /* 定义关键帧动画:显示4秒,其余时间隐藏 */ @keyframes rotateText { 0%, 16% { opacity: 1; visibility: visible; } 20%, 100% { opacity: 0; visibility: hidden; } }
代码说明
- 固定H1的
height和overflow: hidden,确保切换时不会改变页面布局。 - 每个
span对应一组符合规则的文本,通过position: absolute重叠在一起。 - 总动画时长设为20秒(5个条目 × 4秒显示时长),每个条目通过
animation-delay错开显示时间。 - 关键帧
rotateText控制每个文本在对应时间段内可见,其余时间隐藏,循环往复。
内容的提问来源于stack exchange,提问作者Newbie_developer
相关产品推荐
相关产品推荐

