小程序如何实现锚点跳转的效果?
小程序的scroll-view的使用
示例如下:
1.1 .atml
文件:
<scroll-view scroll-y="true" style="height: {{height+'px'}};" scroll-into-view="{{ detail }}" scroll-with-animation="true">
<view id='detail0'> detail0 container </view>
<view id='detail1'> detail1 container </view>
<view id='detail2'> detail2 container </view>
<view id='detail3'> detail3 container </view>
</scroll-view>
style
: 设置该容器的高度信息
scroll-into-view
: 值为某个子元素的 id,滚动到该元素,元素顶部对齐滚动区域顶部
scroll-with-animation
: 是否在设置滚动条位置时使用动画过渡
内部子标签需配置形如上述表示的id
,结合scroll-into-view
的值的变化来实现跳转到锚点的效果
1.2 .js
文件
Page({
data: {
detail: 'detail0', // scroll-into-view的值,即跳转对应的id位置
height: 0, // 屏幕的高度
},
onLoad() {
// 设置scroll-view的容器高度
this.setData({
height: dd.getSystemInfoSync().windowHeight // 获取屏幕高度
})
},
// 设置detail的值以实现滚动到指定位置的效果
scrollToView(e){
const { index } = e.target.dataset
this.setData({
detail: `detail${index}`
})
}
})