JS 特效 词条目录
前端Wiki/JS 特效/滚动与组件/滚动特效

回到顶部按钮

回到顶部按钮:页面滚动一段距离后出现,点击平滑滚回顶部。出现时机用滚动监听(节流版)或 IntersectionObserver;滚动行为用 window.scrollTo({top:0, behavior:"smooth"}),原生支持平滑滚。

细节:按钮 fixed 定位在右下角;做“滚一半才出现”的逻辑别忘了节流;支持 reduced-motion 的用户应降级为瞬时定位(scroll-behavior: smooth 配合媒体查询关闭)。

  • 滚动超过一屏(innerHeight)才显示,淡入而非硬切
  • window.scrollTo({top:0, behavior:"smooth"}) 原生平滑滚动
  • scroll 监听必须节流,或用 rAF 包一层
HTML
<style>
#totop { position: fixed; right: 18px; bottom: 18px; z-index: 50;
         width: 44px; height: 44px; border-radius: 50%; border: none;
         background: #a371f7; color: #fff; font-size: 18px; cursor: pointer;
         box-shadow: 0 6px 16px rgba(167,113,247,.4);
         opacity: 0; visibility: hidden; transform: translateY(10px);
         transition: .3s ease; }
#totop.show { opacity: 1; visibility: visible; transform: none; }
#scrollbox { height: 160px; overflow: auto; position: relative; }
</style>
<div id="scrollbox">
  <div style="height:800px;padding:20px;color:#888">长内容……滚动一段距离后右下角出现按钮</div>
</div>
<button id="totop">↑</button>
<script>
var box = document.getElementById('scrollbox');
var btn = document.getElementById('totop');
box.addEventListener('scroll', function () {
  btn.classList.toggle('show', box.scrollTop > box.clientHeight);
});
btn.addEventListener('click', function () {
  box.scrollTo({ top: 0, behavior: 'smooth' });
});
</script>
本节要点回到顶部 = 滚动超一屏显示 + scrollTo smooth;按钮 fixed 定位,scroll 监听节流。
🔗 相关词条事件DOMCSS 特效