效果: 当页面往下滑动一段距离(例如150px),右下角会实时出现一个圆形标签,点击会将页面滑动至顶端。
实现代码:
wxml:
<!--index.wxml-->
<scroll-view class="aa" scroll-y scroll-top='{{top}}' bindscroll="scrollgo">
<view class="cc">11111111</view>
<view class="cc">22222222</view>
<view class="cc">33333333</view>
<view class="cc">44444444</view>
<view class="cc">55555555</view>
<view class="cc">66666666</view>
<view class="cc">77777777</view>
<view class="cc">88888888</view>
</scroll-view>
<view class="gobtn" hidden='{{isshow}}' catchtap="goTop">
顶部
</view>
wxss :
/**index.wxss**/
page{
height: 100%;
width: 100%;
}
.aa{
width: 100%;
height: 100%;
}
.cc{
width: 100%;
height: 20%;
/* background-color: #0094ff; */
}
.gobtn{
width: 150rpx;
height: 150rpx;
position: fixed;
right: 100rpx;
bottom: 150rpx;
border-radius: 50%;
text-align: center;
line-height: 150rpx;
border: 2px solid chartreuse;
background-color: #0094ff;
}
js:
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
top: 0,
isshow: true
},
// bindscroll 滚动时会触发,然后获取滚动条当前位置
scrollgo: function (e) {
// console.log(e)
if (e.detail.scrollTop > 150) { // 滑动超过300才显示
this.setData({
isshow : false
});
} else {
this.setData({
isshow: true
});
}
},
//回到顶部
goTop: function () { // 点击回到顶部
this.setData({
top: 0 // 用this.setData 才能实时更新界面
});
},
}) //page()
isshow 变量控制右下角的图标是否出现,例子中是滑动超过150px 出现,少于150px隐藏。
最好查看一下官方文档的说明,注意scroll-top 、 bindscroll、catchtap、hidden 的使用方法。
效果图: