我们在浏览商品或者文章的时候,当一屏不够的时候,会不停的往上拖动看更多的内容,当需要回到顶部的时候,手工再去滑动手指控制页面往上翻动,效率非常低。这个时候就需要用到【回到顶部】的按钮来帮我们快速回到顶部。
废话不多说,下面我们来实现这个功能。
这个按钮不是任何时候都需要出现,毕竟是个半透明的悬浮按钮,也会阻碍页面的浏览。
分两种情况:
第一种情况,当页面在顶部的时候,回到顶部按钮是不会出现的。

第二种情况,当页面在离开顶部一定距离的时候,回到顶部按钮出现,如下图:

接下就是对代码的分析了:
在这里我们如果要使用滚动事件的话,小程序规定 最外层一定要使用scroll-view标签进行包裹,然后在设置scroll-y=”true” 意思是允许页面了纵向滚动,scroll-top是滚动到顶部做处理,一般绑定一个事件,
bindscrolltolower同样的原理,滚动到底部做处理,bindscroll表示在滚动的时候出发这个事件。
下面WXML内部的话,就是我们回到顶部的按钮设置,我们在点击它时绑定一个事件goTop,让他的滚动高度等于0,这样它就回到顶部了。
WXML代码:
1 2 3 4 5 6 7 8 9 10 11 | <scroll-view class = "bigWrap" scroll-y= "true" scroll-top= "{{scrollTop}}" bindscroll= "scroll" bindscrolltolower= "scrolltolower" style= "position: absolute; left: 0; top:0; bottom: 0; right: 0;" >
<view class = "com-widget-goTop" bindtap= "goTop" wx: if = "{{floorstatus}}" >
<view class = "icon-gotop" >
顶部
</view>
</view>
</view>
|
登录后复制
JS代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | Page({
data: {
scrollTop: 0
},
goTop: function (e){
this.setData({
scrollTop:0
})
},
scroll: function (e,res){
if (e.detail.scrollTop > 500){
this.setData({
floorstatus: true
});
} else {
this.setData({
floorstatus: false
});
}
})
|
登录后复制
WXSS代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | .bigWrap{
background:#eee;
}
/goTop回到顶部图标start/
.com-widget-goTop {
position: fixed;
bottom: 125px;
right: 5px;
background: rgba(0,0,0,0.48);
border-radius: 50%;
overflow: hidden;
z-index: 500;
}
.com-widget-goTop .icon-gotop{
background-color: rgba(0,0,0,0.8);
display: inline-block;
width: 50px;
height: 50px;
line-height: 68px;
font-size: 12px;
color: #ffffff;
text-align: center;
border-radius: 50%;
background: url() no-repeat center -1110px;
-webkit-background-size: 50px auto;
}
|
登录后复制
更多微信小程序实现【回到顶部】的按钮效果相关文章请关注PHP中文网!