uniapp左右滑动导航栏
时间: 2025-06-30 08:07:18 浏览: 17
### 实现左右滑动导航栏效果的代码示例
以下是一个完整的实现左右滑动导航栏效果的示例代码,结合了 `scroll-view` 组件和触摸事件处理逻辑[^1]。
```html
<template>
<view class="container">
<!-- 头部导航栏 -->
<view class="scroll-con">
<scroll-view
class="scroll-box"
scroll-x="true"
@touchstart="touchStart"
@touchend="touchEnd"
>
<view
class="scroll-item"
:class="current === index ? 'active' : ''"
v-for="(item, index) in routeList"
:key="index"
@click="onchange(index)"
>
{{ item.text }}
</view>
</scroll-view>
</view>
<!-- 内容区域 -->
<view class="content">
<view v-if="current === 0">内容1</view>
<view v-if="current === 1">内容2</view>
<view v-if="current === 2">内容3</view>
<view v-if="current === 3">内容4</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
current: 0,
routeList: [
{ text: "选项1" },
{ text: "选项2" },
{ text: "选项3" },
{ text: "选项4" }
],
touchStartX: 0,
touchStartY: 0
};
},
methods: {
onchange(index) {
this.current = index;
},
touchStart(e) {
this.touchStartX = e.touches[0].clientX;
this.touchStartY = e.touches[0].clientY;
},
touchEnd(e) {
const deltaX = e.changedTouches[0].clientX - this.touchStartX;
const deltaY = e.changedTouches[0].clientY - this.touchStartY;
if (Math.abs(deltaX) > 50 && Math.abs(deltaX) > Math.abs(deltaY)) {
if (deltaX > 0) {
// 向右滑动
if (this.current > 0) {
this.current--;
}
} else {
// 向左滑动
if (this.current < this.routeList.length - 1) {
this.current++;
}
}
}
}
}
};
</script>
<style>
.container {
display: flex;
flex-direction: column;
height: 100vh;
}
.scroll-con {
width: 100%;
overflow: hidden;
background-color: #f8f8f8;
}
.scroll-box {
white-space: nowrap;
display: flex;
}
.scroll-item {
display: inline-block;
padding: 10px 20px;
margin-right: 10px;
border-radius: 5px;
cursor: pointer;
background-color: #ddd;
}
.scroll-item.active {
background-color: #4caf50;
color: white;
}
.content {
flex: 1;
padding: 20px;
background-color: #fff;
}
</style>
```
### 说明
上述代码实现了左右滑动导航栏的效果。通过 `scroll-view` 的 `scroll-x` 属性支持横向滚动,同时使用触摸事件监听用户的滑动手势[^2]。当用户向左或向右滑动时,根据手势方向切换当前选中的导航项,并更新对应的内容。
阅读全文
相关推荐


















