在开发微信小程序时,有时一些视图在手机指定的宽度和高度不够存放,那么可以放在scroll-view中。
1、scroll-view横向滚动
在给scroll-view设置滚动的时候,分为三个步骤:
- 1. 给scroll-view添加scroll - x = "{{true}}"属性
- 2. 给scroll-view添加white-space:nowrap样式
-
3. 给scroll-view中的子元素设置为display:inline-block
具体的示例代码:
1.1、scroll.wxml代码:
<!-- scroll-view横向滚动 -->
<scroll-view class="scroll-view" scroll-x="{{true}}">
<view class="scroll-item bg_red"></view>
<view class="scroll-item bg_green"></view>
<view class="scroll-item bg_yellow"></view>
<view class="scroll-item bg_black"></view>
<view class="scroll-item bg_blue"></view>
<view class="scroll-item bg_orange"></view>
</scroll-view>
1.2、scroll.wxss代码:
.scroll-view {
width: 100%;
height: 100px;
margin-top: 200px;
white-space: nowrap;
}
.scroll-view .scroll-item {
display: inline-block;
width: 100px;
height: 100px;
}
.bg_red {
background: red;
}
.bg_green {
background: green;
}
.bg_yellow {
background: yellow;
}
.bg_black {
background: black;
}
.bg_blue {
background: blue;
}
.bg_orange {
background: orange;
}
2、scroll-view纵向滚动
在给scroll-view设置滚动的时候,分为两个步骤:
- 1. 给scroll-view添加scroll - y = "{{true}}"属性
-
2. 给scroll-view设置高度
具体的示例代码:
1.1、scroll.wxml代码:
<scroll-view class="scroll-view-y" scroll-y="{{true}}">
<view class="scroll-item-y bg_red"></view>
<view class="scroll-item-y bg_green"></view>
<view class="scroll-item-y bg_yellow"></view>
<view class="scroll-item-y bg_black"></view>
<view class="scroll-item-y bg_blue"></view>
<view class="scroll-item-y bg_orange"></view>
</scroll-view>
1.2、scroll.wxss代码:
.scroll-view-y {
width: 100%;
height: 300px;
background: palegoldenrod;
margin-top: 200px;
white-space: nowrap;
}
.scroll-view-y .scroll-item-y {
width: 100%;
height: 180px;
}
.bg_red {
background: red;
}
.bg_green {
background: green;
}
.bg_yellow {
background: yellow;
}
.bg_black {
background: black;
}
.bg_blue {
background: blue;
}
.bg_orange {
background: orange;
}
3、scroll-view滚动相关的事件
属性 | 数据类型 | 默认值 | 主要作用 |
---|---|---|---|
scroll-y | Boolean | false | 允许纵向滚动 |
upper-threshold | Number | 50 | 距离顶部/左边多远时,触发scrolltoupper事件 |
lower-threshold | Number | 50 | 距离底部/右边多远时,触发scrolltolower事件 |
scroll-top | Number | 设置竖向的滚动条位置 | |
scroll-left | Number | 设置横向滚动条的位置 | |
scroll-into-view | String | 值应为某子元素id(id不能以数字开头),设置哪个方向可滚动,则在哪个方向滚动到该元素 | |
scroll-with-animation | Boolean | false | 在设置滚动条位置时使用动画过渡 |
enable-back-to-top | Boolean | false | IOS点击顶部状态栏、安卓双击标题栏时,滚动条返回至顶部,只支持竖向 |
bindscrolltoupper | EventHandle | 滚动到顶部/左边,会触发scrolltoupper事件 | |
bindscrolltolower | EventHandle | 滚动到底部/右边,会触发scrolltolower事件 |
滚动到指定的id元素位置,并且给滚动的过程添加动画
<scroll-view class="scroll-view-y" scroll-into-view="yellow" scroll-with-animation="{{true}}" scroll-y="{{true}}">
<view class="scroll-item-y bg_red"></view>
<view class="scroll-item-y bg_green"></view>
<view id="yellow" class="scroll-item-y bg_yellow"></view>
<view class="scroll-item-y bg_black"></view>
<view class="scroll-item-y bg_blue"></view>
<view class="scroll-item-y bg_orange"></view>
</scroll-view>