微信小程序回到頂部的兩種方式


一,使用view形式的回到頂部
HTML:

<image src='../../img/button-top.png' class='goTop' hidden='{{!floorstatus}}' bindtap="goTop"></image>
1
CSS:

/* 返回頂部 */
.goTop{
  height: 80rpx;
  width: 80rpx;
  position: fixed;
  bottom: 50rpx;
  background: rgba(0,0,0,.3);
  right: 30rpx;
  border-radius: 50%;
}
1
2
3
4
5
6
7
8
9
10
JS:

  // 獲取滾動條當前位置
  onPageScroll: function (e) {
    console.log(e)
    if (e.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },

  //回到頂部
  goTop: function (e) {  // 一鍵回到頂部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '當前微信版本過低,無法使用該功能,請升級到最新微信版本后重試。'
      })
    }
  },
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
27
二.使用scroll-view形式的回到頂部

<scroll-view scroll-y scroll-top='{{topNum}}' bindscroll="scrolltoupper">
<image src='../../img/button-top.png' class='goTop' hidden='{{!floorstatus}}' bindtap="goTop"></image>
1
2
CSS:

/* 返回頂部 */
.goTop{
  height: 80rpx;
  width: 80rpx;
  position: fixed;
  bottom: 50rpx;
  background: rgba(0,0,0,.3);
  right: 30rpx;
  border-radius: 50%;
}
1
2
3
4
5
6
7
8
9
10
JS:

  data:{
    topNum: 0
  }

  // 獲取滾動條當前位置
  scrolltoupper:function(e){
    console.log(e)
    if (e.detail.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },

  //回到頂部
  goTop: function (e) {  // 一鍵回到頂部
    this.setData({
      topNum: this.data.topNum = 0
    });
  },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM