How to set the WeChat applet pop-up window scroll bar to the top

Recently, I found something very annoying. When the pop-up window content of WeChat applet can be scrolled, it must be ensured that it is at the top every time it is opened. After some research, I finally found out how to solve it.

first step

First, you need to wrap the content in your pop-up window with scroll-view tags, like this

  <scroll-view style="height:592rpx" scroll-y="{
    
    {true}}" scroll-top="{
    
    {scroll}}">
  </scroll-view>

Three points need to be noted here.
1. There must be a height. Set height
2. scroll-y="{ {true}}".
3. Set scroll-top="{ {scroll}}".

Step 2

Populate scroll-view

 <scroll-view style="height:592rpx" scroll-y="{
    
    {true}}" scroll-top="{
    
    {scroll}}">
 	<view class="saleUnit">
 		<view  wx:for="{
    
    {5}}" wx:key="index" ></view>
 	</view>
  </scroll-view>

What needs to be noted here is that the height of the element under the scroll-view should not be hard-coded. If it is hard-coded, it will not be able to slide.

The third step is to set scroll in js

在data中定义
data: {
    
    
    scroll: 0,
    }
在弹窗打开时设置
setTimeout(()=>{
    
    
      if (this.data.scroll === 0) {
    
    
        this.setData({
    
    
          scroll: 0.1,
        })
      } else {
    
    
        this.setData({
    
    
          scroll: 0,
        })
      }
     },300)

There are two points to note here

Adding setTimeout here is also one of the bugs. It is guessed that it is not rendered properly. After adding setTimeout, it will take effect.
The same goes for setting 0.1. When setting 0 directly, sometimes it is impossible to scroll to the top. Setting 0.1 solves the problem.

happy ending

If you have any better suggestions, please feel free to communicate~

Guess you like

Origin blog.csdn.net/Yannnnnm/article/details/127448544