The applet page scrolls to the specified position

How to make the page automatically scroll to a certain position (for example, click a certain button, you need to automatically scroll to the position of the corresponding content), it is very simple in the applet, the official provides the API to get the element position and scroll to the target position:

1. Use uni.createSelectorQuery().select().boundingClientRect() to query the position of the element that needs to be scrolled to

2. Scroll to the target position: uni.pageScrollTo()

The same is true for WeChat native, using wx.createSelectorQuery() and wx.pageScrollTo()

Many APIs of the applet are very simple and can be used directly. The following is an example of the overall usage method:

toScroll() {
    
    
  // 1.使用uni.createSelectorQuery()查询到需要滚动到的元素位置
  const query = uni.createSelectorQuery().in(this);
  query.select('.recommend-list').boundingClientRect(data => {
    
    
     console.log(data.top) // 滚动到的位置(距离顶部 px)
    // 到这里我们可以从data中读到top,即离顶部的距离(px)
    // 2使用uni.pageScrollTo()将页面滚动到对应位置
    uni.pageScrollTo({
    
    
	  scrollTop: data.top, // 滚动到的位置(距离顶部 px)
	  duration: 300
	});
  }).exec();
},

Guess you like

Origin blog.csdn.net/weixin_48585264/article/details/129874544