The API and page methods used

API: wx. CreateSelectorQuery, wx. CreateIntersectionObserver

Page method :onPageScroll

Why use the above method?

Wx.createselectorquery: The main solution is to ensure that the elements involved are rendered 100% to the screen after a page is rendered, packaged with an asynchronous method.

getElement(elm, component) {
    const _this = this;
    return new Promise((resolve, reject) => {
      let ss = setInterval(function() {
        let Qy = component ? _this.createSelectorQuery() : wx.createSelectorQuery();
        let a = Qy.select(elm).boundingClientRect(function(res) {
          if (res) {
            clearInterval(ss)
            resolve(res)
          }
        }).exec();
      }, 50);
    });
  }
Copy the code

Wx. CreateIntersectionObserver and onPageScroll role: use pure onPageScroll hidden state display will use high frequency switch caton setData cause page. If only to wx. CreateIntersectionObserver and onPageScroll hide or show, which is to ensure that each method in setData only once, and then caton phenomenon will not appear. The following wx. CreateIntersectionObserver only as a display element

onCreateIntersectionObserver(component,elm) {
    const _this = this;
    this.getElement(elm||".tr-fixed", Component). Then (res => {_this.setData({fixed_top: res.top // Record the top value of the element that is always displayed}); _this.IntersectionObserver = component ? _this.createIntersectionObserver() : wx.createIntersectionObserver() _this.IntersectionObserver.relativeTo(".top-transparent", {
        bottom: 2
      }).observe(elm||'.tr-fixed', (res) => {// show top const {fixed_show} = _this.data;if (fixed_show === false) {
          _this.setData({
            fixed_show: true}); } // display top})}); }Copy the code

In the code above:.top-transparent is a custom reference area. .tr-fixed or ELM for switching hidden and displayed elements (pre-written float top, hidden, there is no CSS only as listener)

<view class="top-transparent"</view> < View class="tr-fixed"</view> <view class= the part that is always displayed (scrollTop less than the top value of this element is hidden, and is displayed if it is detected to cross with a transparent reference element)"fixed-view" wx:if="{{fixed_show}}"> Hidden part (exactly the same as always shown) </view>Copy the code
.top-transparent{ position: fixed; top: 0; left: 0; right: 0; height: 20px; background: transparent; // transparent pointer-events: none; // Make sure that all click events of this element are invalid, i.e. click events penetrate elements lower than it}Copy the code

The following onPageScroll is used as a hidden element only

OnPageScroll (e) {const {fixed_top, fixed_show} = this.dataif(fixed_top ! = undefined && fixed_show) {if (e.scrollTop <= fixed_top) {
        this.setData({
          fixed_show: false})}} // Hide the top head},Copy the code

Code snippets: developers.weixin.qq.com/s/oUhsfCmP7…