(一)横向滚动、纵向滚动
scroll-x scroll-y
<view>
<view class="box">
<!-- 纵向滚动 -->
<scroll-view class="wrapper" scroll-y>
<view id="1" class="view demo-1">A</view>
<view id="2" class="view demo-2">B</view>
<view id="3" class="view demo-3">C</view>
</scroll-view>
<!-- 横向滚动 -->
<scroll-view class="x-wrapper" scroll-x>
<view id="1" class="view demo-1">A</view>
<view id="2" class="view demo-2">B</view>
<view id="3" class="view demo-3">C</view>
</scroll-view>
</view>
</view>
同时配合css
.view {
height: 400px;
width: 100%;
/* 必须是 inline-block 给父元素设置display: flex 不好使 */
display: inline-block;
}
.demo-1 {
background: red;
}
.demo-2 {
background: green;
}
.demo-3 {
background: yellow;
}
.wrapper {
height: 500px;
}
.x-wrapper {
white-space: nowrap;
height: 400px;
margin: 100px 0;
}
(二)scroll-into-view
wxml:
<view class="box">
<!-- 纵向滚动 -->
<scroll-view class="wrapper" scroll-y scroll-into-view="{
{ targetIndex }}" scroll-with-animation="{
{ true }}">
<view id="block1" class="view demo-1">A</view>
<view id="block2" class="view demo-2">B</view>
<view id="block3" class="view demo-3">C</view>
</scroll-view>
<button bindtap="scrollTarget" data-id="1">go A</button>
<button bindtap="scrollTarget" data-id="2">go B</button>
<button bindtap="scrollTarget" data-id="3">go C</button>
</view>
js:
Page({
data: {
targetIndex: 'block1'
},
scrollTarget (e) {
this.setData({
targetIndex: `block${e.currentTarget.dataset.id}`
})
console.log(e.currentTarget.dataset.id)
}
})
涨知识:
1. scroll-into-view 绑定id,当点击按钮的时候,改变 绑定id,达到滚动到可是区域的效果
2. 小程序传参数 需要 在 标签上绑定 data-参数名称,e.currentTarget.dataset.参数名称获取
3. scroll-with-animation 滚动的时候会有动画,缓慢的平滑
4. 每个 view 的 id 不能以 数字开头<