position: sticky;解决样式吸顶真是太给力了;再也不用动态计算距离顶部多少去fixed;
吸顶:滚动条不滚动是原来的位置(relative),滚动条滚动超过该元素位置后就置顶了(如果设置的是top:0)

点击
position:sticky是css定位新增属性;可以说是相对定位relative和固定定位fixed的结合;它主要用在对scroll事件的监听上;简单来说,在滑动过程中,某个元素距离其父元素的距离达到sticky粘性定位的要求时(比如top:100px);position:sticky这时的效果相当于fixed定位,固定到适当位置。

以前写法:

点击查看代码
    <view
         class="header {{tabFixed ? 'navTop': ''}}"
         style='top: {{homePageNavHeight}}PX'
         id="header"
         catchtouchmove='true'
      >
       <tr-eedata bindmyevent="myevent"></tr-eedata>
    </view>
    <view class="descItem">
        <block wx:if="{{cprojectlist.length>0}}">
           <view class="desc" wx:for="{{cprojectlist}}" wx:key="index">
              <project-card item="{{item}}" />
           </view>
        </block>
        <view class="nodata-con" wx:else>
           <image class="imgs" src="/images/store/empty.png" mode="widthFix" />
           <view class="nodataCon">阿欧,更换搜索条件试试看~</view>
        </view>
    </view>
样式
.header {
  padding: 20rpx 0;
  background-color: #f6f6f6;
}

.header.navTop {
  position: fixed;
  top: 151PX; // 默认可不写
  z-index: 99;
  width: 100%;
  background-color: #fff;
  border-bottom: 0.5px solid #E9E9E9;
}
// js
 getAreaHeight () {
    const query = wx.createSelectorQuery();
    query
      .select('.swiperCard')
      .boundingClientRect()
      .select('.homepage__nav')
      .boundingClientRect()
      .exec(res => {
        //res就是元素的信息 的数组
        if(res && res.length){
          this.setData({
            swiperCardHeight: res[0].height + 1,
            swiperCardBottom: res[0].bottom,
            homePageNavHeight:res[1].height
          })
        }
    })
  },

position: sticky;只需要这样

     <view>
         <view class="header" id="header" catchtouchmove='true'>
            <tr-eedata bindmyevent="myevent"></tr-eedata>
         </view>
         <view class="descItem">
            <block wx:if="{{cprojectlist.length>0}}">
               <view class="desc" wx:for="{{cprojectlist}}" wx:key="index">
                  <project-card item="{{item}}" />
               </view>
            </block>
            <view class="nodata-con" wx:else>
               <image class="imgs" src="/images/store/empty.png" mode="widthFix" />
               <view class="nodataCon">阿欧,更换搜索条件试试看~</view>
            </view>
         </view>
      </view>

样式
.header {
  position: sticky;
  top: 0;
  padding: 20rpx 0;
  background-color: #f6f6f6;
}
再也不用js代码计算top的距离啦


只需要将吸顶元素的标签和他后面的兄弟元素外面加一个父级元素,父级元素样式可以什么也不设置,吸顶元素的样式加上 position: sticky; top: 0;
要加一个父级,子级吸顶加position: sticky; 和偏移量; offset偏移量bottom,left,top,right,任选一个去设置达到想要的效果

还有一点要注意:
position设置了top、right、bottom、left之后,height和width设置为多大都不起作用。

学习了博客 https://blog.csdn.net/qq_34629352/article/details/106112062
https://blog.csdn.net/qq_35585701/article/details/81040901?spm=1001.2014.3001.5502
BFC: https://www.cnblogs.com/heimanba/p/3774086.html

posted on 2022-06-08 17:57  sandy.simple  阅读(63)  评论(0编辑  收藏  举报