使用 ant-design-vue 的 tabs 组件实现滚动条滚到 tabs 位置
在 vue 页面中使用 ant-design-vue 的 tabs 组件时,可以实现滚动条滚动到 tabs 位置时吸顶,而向上滚动时也能正常显示 tabs 上面的内容。
思路:
代码示例:
<template>
<div ref="scrollPositionContainer" class="h-full bg-[#F5F5F5] py-[14px] px-[20px] overflow-y-auto" @scroll="handleScroll">
<div class="parent bg-primary">
<product-info />
<a-tabs v-model:activeKey="activeKey" :tabBarGutter="30" class="tabs w-auto h-auto bg-[#FFFFFF] py-[14px] px-[20px] mt-10px box-border" :class="isFixed ? 'isfixed' : ''">
<a-tab-pane key="performance" tab="111">
<perform-trend-tab />
</a-tab-pane>
<a-tab-pane key="style" tab="222" force-render>Content of Tab Pane 2</a-tab-pane>
<a-tab-pane key="analys" tab="333">Content of Tab Pane 3</a-tab-pane>
</a-tabs>
</div>
</div>
</template>
<script>
import { Ref } from 'vue';
import { nextTick } from 'vue';
import { onActivated } from 'vue';
export default {
setup() {
const scrollTop: Ref<number> = ref(0);
const barOffsetTop: Ref<number> = ref(0);
const isFixed: Ref<boolean> = ref(false);
const scrollPositionContainer = ref<Element | null>(null);
const handleScroll = (e: any) => {
scrollTop.value = e.target.scrollTop;
const top = window.pageYOffset || e.target.scrollTop;
// 判断 Tabs 距顶和滚动距离,超过就让 a-tabs 的 class 加上 isfixed 的样式
isFixed.value = top >= barOffsetTop.value ? true : false;
}
onActivated(() => {
scrollPositionContainer.value?.scrollTo({ top: scrollTop.value });
nextTick(() => {
// 获取 Tabs 距顶的距离
barOffsetTop.value += document.getElementsByClassName('tabs')[0]?.offsetTop;
})
})
return {
scrollTop,
barOffsetTop,
isFixed,
scrollPositionContainer,
handleScroll
}
}
}
</script>
<style lang="less" scoped>
:deep(.ant-tabs > .ant-tabs-nav) {
margin: 0;
background: #fff;
padding-left: 20px;
box-sizing: border-box;
}
:deep(.ant-tabs-content-holder) {
height: auto;
overflow-y: scroll;
}
.parent {
position: relative;
}
.isfixed{
position: fixed;
top: 0;
}
</style>注意:
立即学习“前端免费学习笔记(深入)”;
以上就是Vue中如何使用ant-design-vue的Tabs组件实现滚动吸顶效果?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号