当前位置:网站首页>Wechat applet slides to the top

Wechat applet slides to the top

2022-06-10 15:05:00 yechaoa

effect :

Click the icon in the lower right corner of the above figure to slide to the top . It's very simple , But there are some small details .

1. Determine the position of the icon button

Use the absolute position to fix it in the lower right corner .

wxml:

<icon type="download" size="45" color="#4caf50" bindtap='scrollTop'/>

The official download icon is used here , Then I changed the color .

wxss:

icon[type=download] {
   position: fixed;
   bottom: 30px;
   right: 20px;
   transform: rotate(180deg);
}
  • In order not to follow the slide , Revised position by fixed.
  • Originally, the arrow was downward , Use transform: rotate(180deg) rotate 180 Degrees up .

2. The binding event

bindtap='scrollTop'

   scrollTop: function() {
      wx.pageScrollTo({
         scrollTop: 0,
         duration: 300
      })
   },

In the event , We used the official API wx.pageScrollTo, Two parameters , One is the sliding position , One is the execution time .

Here we are , The function of sliding to the top is simply realized .

3. Advanced

Why is there such a step , Because I found that whether the sliding distance is far or near , The execution duration is 300, Can it be optimized , It can .

WeChat page There is one of them. onPageScroll Method ( And onLoad Level ), Listen to user sliding page events . Then we can dynamically set the execution time according to the sliding distance .

Define the duration as a variable

data: {
      scrollDuration: 500,
   },

Assign a value in the listening event

   onPageScroll: function(e) {
      console.log(e.scrollTop)
      this.setData({
         scrollDuration: e.scrollTop / 2
      });
   }
  • e.scrollTop Is the page sliding distance
  • e.scrollTop / 2 Is the execution time , You can also set other values
  • Official tip : Please avoid onPageScroll Too frequent execution in setData And so on - Operation of rendering layer communication .

Modify the sliding method

   scrollTop: function() {
      wx.pageScrollTo({
         scrollTop: 0,
         duration: this.data.scrollDuration
      })
   },

ok, This is all done .

原网站

版权声明
本文为[yechaoa]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101443243285.html