我们先看一下效果吧,直接上图。
第一种情况,当页面在顶部的时候,回到顶部按钮是不会出现的。
第二种情况,当页面在离开顶部一定距离的时候,回到顶部按钮出现
接下就是对代码的分析了:
在这里我们如果要使用滚动事件的话,小程序规定 最外层一定要使用scroll-view标签进行包裹,然后在设置scroll-y=”true” 意思是允许页面了纵向滚动,scroll-top是滚动到顶部做处理,一般绑定一个事件,bindscrolltolower同样的原理,滚动到底部做处理,bindscroll表示在滚动的时候出发这个事件。下面WXML内部的话,就是我们回到顶部的按钮设置,我们在点击它时绑定一个事件goTop,让他的滚动高度等于0,这样它就回到顶部了。
WXML代码:
-
<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代码:
-
//回到顶部按钮
-
Page({
-
data: {
-
scrollTop: 0
-
},
-
goTop: function(e){
-
this.setData({
-
scrollTop:0
-
})
-
},
-
scroll:function(e,res){
-
// 容器滚动时将此时的滚动距离赋值给 this.data.scrollTop
-
if(e.detail.scrollTop > 500){
-
this.setData({
-
floorstatus: true
-
});
-
}else {
-
this.setData({
-
floorstatus: false
-
});
-
}
-
})
WXSS代码:
-
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(http://m.dev.vd.cn/static/xcx/v1/goo/w_2-3451cc437e.png) no-repeat center -1110px;
-
-webkit-background-size: 50px auto;
-
}
|