uniapp scroll-view垂直滑动 按照距离激活tab
时间: 2025-06-12 20:30:02 浏览: 16
### 实现 UniApp 中 `scroll-view` 垂直滑动并动态激活 Tab
在 UniApp 开发中,可以通过监听 `scroll-view` 的滚动事件来获取当前的垂直滑动距离,并基于该距离计算应激活哪个 Tab。以下是具体实现方法:
#### 1. 使用 `bindscroll` 或者 `@scroll` 绑定滚动事件
通过绑定 `scroll-view` 的滚动事件,可以实时获取到用户的滚动位置数据。
```html
<template>
<view class="container">
<!-- Tab 导航 -->
<view class="tabs">
<view
v-for="(item, index) in tabs"
:key="index"
:class="{ active: currentIndex === index }"
@click="switchTab(index)"
>
{{ item }}
</view>
</view>
<!-- 可滚动区域 -->
<scroll-view
class="scroll-area"
scroll-y
@scroll="handleScroll"
:style="'height:' + windowHeight + 'px;'"
>
<view
v-for="(section, idx) in sections"
:key="idx"
:id="'section-' + idx"
class="section"
>
{{ section }}
</view>
</scroll-view>
</view>
</template>
```
---
#### 2. 数据结构定义
为了方便管理 Tabs 和对应的内容区块高度,需预先设定好相关数据。
```javascript
<script>
export default {
data() {
return {
tabs: ['标签一', '标签二', '标签三'], // 定义 Tab 名称
sections: ['内容一', '内容二', '内容三'], // 对应的内容部分
scrollTopList: [], // 存储各部分内容的起始滚动高度
currentIndex: 0, // 当前选中的 Tab 索引
windowHeight: 600 // 设置可滚动视图的高度 (可根据实际需求调整)
};
},
mounted() {
this.calculateSectionHeights(); // 初始化时计算各个区块的高度
},
methods: {
calculateSectionHeights() { // 计算每个 content 部分的起始滚动高度
const query = uni.createSelectorQuery().in(this);
Promise.all(
Array.from({ length: this.sections.length }, (_, i) =>
new Promise(resolve => {
query.select(`#section-${i}`).boundingClientRect(rect => resolve(rect)).exec();
})
)
).then(results => {
let currentTop = 0;
results.forEach((rect, index) => {
currentTop += rect.top; // 获取相对顶部的距离
this.scrollTopList.push(currentTop); // 将其加入列表
});
});
},
handleScroll(e) { // 处理滚动事件
const scrollTop = e.detail.scrollTop;
for (let i = 0; i < this.scrollTopList.length; i++) {
if (
scrollTop >= this.scrollTopList[i] &&
scrollTop < (this.scrollTopList[i + 1] || Infinity)
) {
this.currentIndex = i; // 更新当前索引
break;
}
}
},
switchTab(index) { // 手动点击切换 Tab
this.currentIndex = index;
const targetId = '#section-' + index;
uni.pageScrollTo({
selector: targetId,
duration: 300
});
}
}
};
</script>
```
---
#### 3. 样式设计
为确保界面美观且功能正常运行,需要合理布局样式。
```css
<style scoped>
.container {
display: flex;
flex-direction: column;
}
.tabs {
display: flex;
justify-content: space-around;
background-color: #f7f7f7;
padding: 10px 0;
}
.tabs view {
padding: 5px 10px;
border-bottom: 2px solid transparent;
}
.tabs .active {
color: blue;
font-weight: bold;
border-bottom-color: blue;
}
.scroll-area {
overflow-y: auto;
}
.section {
height: 400px; /* 模拟每节内容的高度 */
text-align: center;
line-height: 400px;
}
</style>
```
---
### 关键点解析
- **滚动事件监听**:通过 `@scroll` 动态捕获用户滚动行为,从而更新当前活动状态[^1]。
- **DOM 节点测量**:利用 `uni.createSelectorQuery()` 测量 DOM 元素的位置和尺寸,以便精确判断滚动范围[^2]。
- **性能优化**:避免频繁重新计算节点高度,在初始化阶段完成所有必要测量工作。
---
阅读全文
相关推荐


















