应用场景:需要在使用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;
}