本节主要讲解 scroll-view 在页面上的使用,长列表的渲染。
# scroll-view 滑动效果实现头部导航栏

导航的滑动区域需要实现左右滑动效果,左右滑动这个在信息资讯设计下很常见,可以选用 Uniapp 中基础组件 scroll-view 容器,在遇到与左右或者上下互动局部内容的时候,可以考虑组件 scroll-view,配置查看scroll-view,示例代码:
<scroll-view class="scroll-view" scroll-x="true" scroll-left="120">
<view class="item uni-bg-red">A</view>
<view class="item uni-bg-green">B</view>
<view class="item uni-bg-blue">C</view>
</scroll-view>
@前端进阶之旅: 代码已经复制到剪贴板
在方位x轴上进行参数设置,即设置 scroll-x="true",即可实现,左右滑动,一切就是那么简单…
但是当你以为一切就这样搞定的时候,可是并没有左右排列,肿么办?

其实是关于 scroll-view 失效的问题,复制官方代码代码后会发现 scroll-view 横向滚共不生效,其实是没有设置好样式,将 scroll-view 容器设置宽度,并设置 white-space: nowrap; scroll-view 容器的每一项都设置宽度和 display:inline-block:
.scroll-view {
width: 100%;
white-space: nowrap;
.item {
position: relative;
display: inline-block;
width: 218rpx;
padding-bottom:16rpx;
margin-right: 16rpx;
line-height: 34rpx;
}
}
@前端进阶之旅: 代码已经复制到剪贴板
# 通过绑定 class/style 实现active滑块

这块的交互是点击触发实现滑块滑动至被触发的项,以及被触发的项实现样式切换。
<scroll-view class="scroll-view" scroll-x>
<view class="item" v-for="(item, index) in navList" :class="{active: curNav == item.id}" :key="item.id" @click="switchNav(item.id, index)">
<view class="desc">{{item.name}}</view>
</view>
<view class="slide" :style="'width: '+ sliderWidth +'rpx;transform: translateX('+ sliderOffset +'rpx)'"></view>
</scroll-view>
// 导航切换
switchNav(id, index) {
this.curNav = id
this.sliderWidth = index == 1 ? 140 : 60;
this.sliderOffset = 126 * index + (index > 1 ? 80 : 16) + (index == 0 && 16);
// 加载数据
this.getRelatedVideo(id)
}
.scroll-view {
position: fixed;
top: 0;
width: 100%;
white-space: nowrap;
text-align: center;
line-height: 86rpx;
color: #333;
.item {
position: relative;
display: inline-block;
min-width: 126rpx;
padding: 0 20rpx;
line-height: 34rpx;
padding-bottom: 16rpx;
<!-- 触发项样式 -->
&.active{
color:#f32628;
}
}
}
<!-- 滑块样式 -->
.slide {
position: absolute;
width: 60rpx;
height: 4rpx;
left: 0;
bottom: 0rpx;
background: #f32628;
transition: transform 0.3s;
}
