position: sticky;
作者:互联网
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
标签:bottom,样式,res,top,sticky,position 来源: https://www.cnblogs.com/wangwenhui/p/16347361.html