欢迎光临,了解微信小程序开发,就上易用通!

制作回到顶部按钮

发布:2018-01-25 09:42浏览: 来源:网络 作者:tianshu

我们先看一下效果吧,直接上图。

 

第一种情况,当页面在顶部的时候,回到顶部按钮是不会出现的。
制作回到顶部按钮(图1)

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

制作回到顶部按钮(图2)

接下就是对代码的分析了: 
在这里我们如果要使用滚动事件的话,小程序规定 最外层一定要使用scroll-view标签进行包裹,然后在设置scroll-y=”true” 意思是允许页面了纵向滚动,scroll-top是滚动到顶部做处理,一般绑定一个事件,bindscrolltolower同样的原理,滚动到底部做处理,bindscroll表示在滚动的时候出发这个事件。下面WXML内部的话,就是我们回到顶部的按钮设置,我们在点击它时绑定一个事件goTop,让他的滚动高度等于0,这样它就回到顶部了。

 

WXML代码:
  1.   <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;">
  2.      //*********************
  3.       <view class="com-widget-goTop" bindtap="goTop" wx:if="{{floorstatus}}">
  4.             <view class="icon-gotop">
  5.                 顶部
  6.             </view>
  7.       </view>
  8.       //*********************
  9.   </view>


JS代码:
  1. //回到顶部按钮
  2. Page({
  3. data: {
  4.     scrollTop: 0
  5.     },
  6. goTop: function(e){
  7.     this.setData({
  8.         scrollTop:0
  9.     })
  10. },
  11. scroll:function(e,res){
  12. // 容器滚动时将此时的滚动距离赋值给 this.data.scrollTop
  13. if(e.detail.scrollTop > 500){
  14.      this.setData({
  15.         floorstatus: true
  16.      });
  17. }else {
  18.      this.setData({
  19.         floorstatus: false
  20.      });
  21.     }
  22.     })


WXSS代码:
  1. bigWrap{
  2. background:#eee;
  3. }
  4. /goTop回到顶部图标start/
  5. .com-widget-goTop {
  6. position: fixed;
  7. bottom: 125px;
  8. right: 5px;
  9. background: rgba(0,0,0,0.48);
  10. border-radius: 50%;
  11. overflow: hidden;
  12. z-index: 500;
  13. }
  14. .com-widget-goTop .icon-gotop{
  15. background-color: rgba(0,0,0,0.8);
  16. display: inline-block;
  17. width: 50px;
  18. height: 50px;
  19. line-height: 68px;
  20. font-size: 12px;
  21. color: #ffffff;
  22. text-align: center;
  23. border-radius: 50%;
  24. background: url(https://m.dev.vd.cn/static/xcx/v1/goo/w_2-3451cc437e.png) no-repeat center -1110px;
  25. -webkit-background-size: 50px auto;
  26. }





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。