如何实现限定在FirstScene内的竖线向上GSAP动画
问题分析
- CSS语法错误:
.line中的width=10px是无效写法,应为width: 10px; - 容器未设置溢出隐藏:
.FirstScene缺少overflow: hidden,导致超出容器的元素会显示出来 - 动画起始位置错误:
yPercent:10会让竖线基于当前定位向下偏移自身高度的10%,结合.line的top:50%定位,导致部分竖线超出容器底部
解决方案
步骤1:修正CSS
- 给
.FirstScene添加overflow: hidden,确保容器内超出部分被隐藏 - 修正
.line的width属性写法,并调整定位确保水平居中且初始状态完全在容器内 - 修复
.linkStyle类选择器的语法错误(之前漏写了.) - 调整
body高度为100vh,确保占满视口高度
修改后的CSS:
* { margin: 0; padding: 0 } .topnav { position: sticky; top: 0; font-size: x-large; background-color: black; overflow: hidden; z-index: 1; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: black; } li { float: right; padding: 8px; color: white; display: inline; } .linkStyle { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li i { color: white; text-decoration: none; } li a { color: white; text-decoration: none; } #li-left { float: left; } body { margin: 0; height: 100vh; } .FirstScene { background-color: black; position: absolute; top: 0; right: 0; bottom: 0; left: 0; overflow: hidden; } .line { left: 50%; bottom: 0; width: 10px; height: 50%; position: absolute; transform: translateX(-50%); } .vertical-line { border-left: 6px solid blue; height: 100%; }
步骤2:调整GSAP动画
让竖线从容器底部(完全在内部)向上移动到容器顶部,修改动画目标为.line,设置起始位置为容器底部,结束位置为容器顶部:
gsap.fromTo(".line", { yPercent: 0 }, { yPercent: -100, duration: 5 });
步骤3:修正HTML中的Link标签
若未使用React等框架,需将Link标签改为普通<a>标签,避免渲染错误:
<li id="li-left"> <a href="/" class="linkStyle"> MINA IBRAHIM </a> </li> <li> <a href="/about" class="linkStyle"> .about() </a> </li>
效果说明
修改后,竖线会从容器底部(完全处于内部)向上平滑移动到容器顶部,全程不会超出.FirstScene容器范围,符合需求。
内容的提问来源于stack exchange,提问作者Mina Samy Ibrahim
相关产品推荐
相关产品推荐

