Sometimes we need to scroll to a certain location (click on the directory at the top and scroll to the corresponding location below), so how do we do this in applets?

1. Use wx.createsElectorQuery ().select().boundingClientRect() to find the element position to scroll to 2. Use wx.pagescrollto () to scroll the page to the appropriate locationCopy the code

The official documentation wx. CreateSelectorQuery () developers.weixin.qq.com/miniprogram…

Wx.pagescrollto ()

Developers.weixin.qq.com/miniprogram…

ScrollTo () {// 1. Use wx.createselectorquery () to find the element position to scrollTo. Wx.createselectorquery ().select('.bb4').boundingclientrect (res // 2 Use wx.pagescrollto () to scroll the page to the corresponding position wx.pagescrollto ({scrollTop: Duration: 0 // If no transition animation is needed, set to 0 (ms)})}).exec()}Copy the code

Once you’ve done it, try the above method, which scrolls the target location to the top of the page. So what if we want the target position to be in the middle of the screen? Subtract half the height of the page from the top of the element.

ScrollTo () {// 1. Use wx.createselectorquery () to find the element position to scrollTo. Wx.createselectorquery ().select('.bb4').boundingclientrect (res = > {/ / 2. WindowHeight (px) wx.getSystemInfo({success(ress) {wx.pagesCrollto ({// 3. ScrollTop: res.top-ress.windowheight /2 + 50, duration: 200})})}).exec()}Copy the code