在開發微信小程序時,會遇到需要橫向滑動的情況。但講道理,微信小程序的 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="width:{{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;
width: 750rpx;
height: 80rpx;
.item-container {
display: flex;
flex-direction: row;
.color-item {
text-align: center;
line-height: 80rpx;
color: white;
width:200rpx;
min-width: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;
width: 750rpx;
height: 80rpx;
display: flex;
flex-direction: row;
.color-item {
text-align: center;
line-height: 80rpx;
color: white;
width:200rpx;
min-width:200rpx;
height:80rpx;
margin-right:20rpx;
}
.text-item {
color: red;
}
}
.scroll-area:last-child {
white-space: nowrap; // 可變長度的文字內容要加上這一個
}
}
</style>