使用CSS动画无法实现navbar导航栏菜单文字垂直翻转效果
实现思路
- 给导航项父容器
<li>设置固定高度 +overflow: hidden,超出可视区域的文字会被隐藏 - 每个导航链接内放置两个相同内容的文本元素,分别在初始可视位置、底部隐藏位置
- hover时给链接添加上移动画,让上方文本移出可视区、下方文本移入可视区,实现「文字向上滑出、从底部滑入回到原位」的滚动效果
完整可运行代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hover Flip Navbar</title> <style> * { margin: 0; padding: 0; border: 0; vertical-align: baseline; background: transparent; font-weight: normal; text-decoration: none; outline: none; box-sizing: border-box; } .wrapper { width: 90%; margin: 0 auto; max-width:1100px; } header { height: 100px; padding: 20px 0; } header nav ul { list-style: none; display: flex; justify-content: space-between; } header nav ul li { font-size: 23px; position: relative; /* 固定高度+溢出隐藏,仅显示单行文本高度 */ height: 32px; overflow: hidden; } header nav ul li a { display: block; transition: transform .3s ease; color: #000; } /* 文本块固定行高,保证上下对齐 */ header nav ul li a span { display: block; height: 32px; line-height: 32px; } header nav ul li a:hover { /* 向上位移刚好一行文本的高度,显示下方的重复文本 */ transform: translateY(-32px); } div.video iframe { margin-top: 30px; } </style> </head> <body> <header> <nav> <section class="wrapper"> <ul> <li> <a href="#"> <span>About</span> <span>About</span> </a> </li> <li> <a href="#"> <span>Project</span> <span>Project</span> </a> </li> <li> <a href="#"> <span>Resume</span> <span>Resume</span> </a> </li> </ul> </section> </nav> </header> <div class="video"> <section class="wrapper"> <iframe width="560" height="315" src="https://www.youtube.com/embed/WeUfsRce9_M" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <h3>如果stackoverflow代码片段平台不支持iframe,可点击下方视频链接查看</h3> <a href="https://www.youtube.com/embed/WeUfsRce9_M" target="_blank" >视频链接</a> </section> </div> </body> </html>
如果需要调整动画速度,修改transition属性里的.3s参数即可。
内容的提问来源于stack exchange,提问作者ABHIJITH EA
相关产品推荐
相关产品推荐

