微信小程序 scroll-view 之横向滑动注意事项及示例
在开发微信小程序时,会遇到需要横向滑动的情况。但讲道理,微信小程序的 scroll-view 不太好用。
对于 scroll-view
设置的 width``height
用来设置组件本身的宽和高。对于放置其中的元素,要形成滑动,需要满足以下两个条件:
- scroll-view 在该方向(x方向,或者y方向)上的滑动选项被打开: 横向要设置
scroll-x="true"
,纵向要设置scroll-y="true"
- 元素在某一方向上的长度比 scroll-view 在该方向上的长度数值更大,如要实现横向滑动,则 scroll-view 内的元素(可以是一个或者多个)的总宽度要比 scroll-view 的 width 要大
主要存在以下几个问题:
在2.7以前,当需要在 scroll-view
微信小程序2.7以前,因为无法直接对 scroll-view 设置 flex 页面,来实现在 x 方向上放置元素,通常的做法是在这些元素上面再套一个容器,同时还要手动来计算这个容器的宽度
这样做的坏处是:
1、*多了一个 view
2、手动计算容器宽度在一些可变宽度元素存在时,有问题(尽管纯文字内容也可以使用 canvas 来实现参考,但很麻烦)
<template>
<view class="container">
<scroll-view
class="scroll-area"
scroll-x="true">
<view class="item-container" style="{{colorWidth}}rpx;">
<repeat for="{{colors}}">
<view class="color-item" style="background-color:{{item}}">{{item}}</view>
</repeat>
</view>
</scroll-view>
</view>
</template>
<script>
import wepy from 'wepy'
export default class Demo extends wepy.page {
data = {
colors: ['red', 'blue', 'black', 'yellow', 'lightgray', 'pink']
}
computed = {
colorWidth () {
let itemWidth = 200
let gap = 20
let width = (itemWidth + gap) * this.colors.length
return width
}
}
}
</script>
<style lang="less">
.container {
display: flex;
flex-direction: column;
.scroll-area {
margin-top: 50rpx;
750rpx;
height: 80rpx;
.item-container {
display: flex;
flex-direction: row;
.color-item {
text-align: center;
line-height: 80rpx;
color: white;
200rpx;
min-200rpx;
height:80rpx;
min-height: 90rpx;
margin-right:20rpx;
}
}
}
}
</style>
在2.7以后
可以使用 enable-flex="true"
让上面的尴尬情况得到缓解,不足之处在于, scroll-view 会在 x 方向上挤压嵌套在其中的元素(亲测 y 方向没有这个问题),可以通过设置元素的 min-width
解决
<template>
<view class="container">
<scroll-view
class="scroll-area"
scroll-x="true"
enable-flex="true">
<repeat for="{{colors}}">
<view class="color-item" style="background-color:{{item}}">{{item}}</view>
</repeat>
</scroll-view>
<scroll-view
class="scroll-area"
scroll-x="true"
enable-flex="true">
<repeat for="{{textList}}">
<view class="text-item">{{item}}</view>
</repeat>
</scroll-view>
</view>
</template>
<script>
import wepy from 'wepy'
export default class Demo extends wepy.page {
data = {
textList: ['0-0', '1-1lin24-1lin24', '2-1lin24-1lin24', '3-1lin24-1lin24-1lin24', '4-1lin24'],
colors: ['red', 'blue', 'black', 'yellow', 'lightgray', 'pink']
}
}
</script>
<style lang="less">
.container {
display: flex;
flex-direction: column;
.scroll-area {
margin-top: 50rpx;
750rpx;
height: 80rpx;
display: flex;
flex-direction: row;
.color-item {
text-align: center;
line-height: 80rpx;
color: white;
200rpx;
min-200rpx;
height:80rpx;
margin-right:20rpx;
}
.text-item {
color: red;
}
}
.scroll-area:last-child {
white-space: nowrap; // 可变长度的文字内容要加上这一个
}
}
</style>