vue3实现滑动后回到顶部功能

应用场景:需要在使用naiveUI的n-drawer抽屉组件中实现回到顶部功能。

在 Web 标准中,scrollTo 方法的 behavior 参数有 2 种合法值:
1、‘auto’ (默认)
效果:瞬间跳转,无动画效果

// 立即滚动到顶部
element.scrollTo({ top: 0, behavior: 'auto' });

2、 ‘smooth’
效果:平滑滚动,带缓动动画

// 平滑滚动到顶部
element.scrollTo({ top: 0, behavior: 'smooth' });

注意:在监听滚动事件时,获取容器需要在开发者工具中通过DOM查询找到真实滚动容器!

主要代码如下:

<NDrawer v-model:show="algorithmVisible" class="h-100% overflow-y-auto" display-directive="show" @mask-click="()=>algorithmVisible='true'">
    <NDrawerContent :native-scrollbar="false" closable  ref="drawerContent" class="drawer-content">
    	<NButton v-if="showBackToTop" type="primary" class="back-to-top" @click="handleBackToTop"></NButton>
      	<!-- 实际业务代码-->
    </NDrawerContent>
  </NDrawer>
watch(()=>algorithmVisible.value, () => {
  if (algorithmVisible.value) {
    nextTick(()=>{
      // 通过DOM查询找到真实滚动容器(可能需要根据实际结构调整选择器)
      realScrollContainer = document.querySelector('.n-scrollbar-container');
      console.log("🚀 ~ nextTick ~ realScrollContainer:", realScrollContainer)
      // 手动绑定事件
      if (realScrollContainer) {
        realScrollContainer.addEventListener('scroll', handleScroll,{capture:true});
      }
    })
  }
},{immediate:true});

// 监听滚动
const handleScroll = () => {
  const scrollContainer = document.querySelector('.n-scrollbar-container');
  if (scrollContainer) {
    showBackToTop.value = scrollContainer.scrollTop > 200;
  }
};

// 回到顶部
const handleBackToTop = () => {
  realScrollContainer?.scrollTo({ top: 0, behavior: 'auto' });
};

onBeforeUnmount(() => {
  if (realScrollContainer) {
    realScrollContainer.removeEventListener('scroll', handleScroll);
  }
});
.back-to-top{
  position:fixed;
  z-index:999;
  bottom:80px;
  right:40px;
  width: 40px;
  height: 40px;
  background-color: transparent;
  border:1px solid white;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding:28px 32px 25px 22px;
  font-size: 24px;
  cursor: pointer;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值