通过监听滚动事件,结合 CSS 定位与 JavaScript 动态计算,可让 <h1> 在页面滚动时平滑上移并同步缩小字体(300px→50px),营造视差与聚焦效果。
通过监听滚动事件,结合 css 定位与 javascript 动态计算,可让 `
` 在页面滚动时平滑上移并同步缩小字体(300px→50px),营造视差与聚焦效果。
要实现滚动过程中 <h1> 文字垂直上移 + 字体渐变缩小的双重动画效果,关键在于:
✅ 使用 position: fixed 确保元素脱离文档流、独立定位;
✅ 利用 scrollY(或兼容性更强的 scrollTop)获取滚动进度;
✅ 将滚动距离映射为 top 偏移量与 font-size 值,实现线性过渡;
✅ 配合 transform: translate(-50%, -50%) 实现精准居中,避免因 top 变化导致抖动。
以下是优化后的完整实现方案(兼容现代浏览器,含防抖与边界保护):
HTML(添加 ID 并精简结构):
<body>
<div class="container">
<h1 id="scrollingTitle">NBA</h1>
</div>
<!-- 确保页面有足够高度以触发滚动 -->
<div style="height: 200vh; background: #000;"></div>
</body>CSS(核心定位与基础样式):
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: black;
overflow-x: hidden;
}
#scrollingTitle {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 300px;
color: #18408B;
font-weight: 900;
text-shadow: 0 0 20px rgba(24, 64, 139, 0.4);
z-index: 10;
margin: 0;
line-height: 1;
}JavaScript(健壮的滚动响应逻辑):
const title = document.getElementById('scrollingTitle');
const maxFontSize = 300;
const minFontSize = 50;
const maxTopPercent = 50; // 初始居中位置(top: 50%)
const minTopPercent = -20; // 滚动到底部时上移至顶部上方
// 防抖函数(避免高频触发影响性能)
function debounce(fn, delay) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(fn, delay);
};
}
function updateTitlePosition() {
const scrollY = window.scrollY;
const docHeight = document.documentElement.scrollHeight - window.innerHeight;
const scrollProgress = docHeight > 0 ? Math.min(scrollY / docHeight, 1) : 0;
// 计算字体大小:300px → 50px 线性衰减
const fontSize = Math.max(minFontSize, maxFontSize - scrollProgress * (maxFontSize - minFontSize));
// 计算垂直位置:从 50% 上移至 -20%,增强视觉上升感
const topPos = maxTopPercent - scrollProgress * (maxTopPercent - minTopPercent);
title.style.fontSize = `${fontSize}px`;
title.style.top = `${topPos}%`;
}
// 监听滚动,使用防抖提升性能
window.addEventListener('scroll', debounce(updateTitlePosition, 16)); // ~60fps
updateTitlePosition(); // 初始化位置? 注意事项:
- 避免直接修改 h1 的 margin-top 或 padding-top,会导致布局重排,性能差且难控制;
- transform: translate() 比纯 top 更高效(利用 GPU 加速),但此处需 top 配合百分比实现跨视口平滑移动;
- 若需更精细控制(如缓动曲线),可将 scrollProgress 传入 easeOutCubic 等缓动函数替代线性映射;
- 移动端需额外处理 touchmove 事件(本例默认适配,因 scroll 事件在主流移动端浏览器中同样触发)。
该方案兼顾可读性、性能与视觉表现,适用于品牌页首屏动效、沉浸式导航标题等场景。

















