position:sticky是css新增的一个属性,意为粘性定位,主要是用在对 scroll 事件的监听上,在滑动过程中,某个元素距离其父元素的距离达到 sticky 的要求时(比如给下图中的红色盒子添加样式position:sticky; top:20px);那么该红色盒子向上滚动,距离父元素的距离达到20px时,会固定到适当的位置,效果是relative与fixed的完美结合。
/2021/10/4c4f7cd4.gif" /2021/10/4c4f7cd4.gif" alt="gift.gif" width="463" height="206" style="width: 463px;height: 206px
该新增属性的应用非常广泛,好东西大家都喜欢借鉴嘛~ 比如饿了么微信小程序端的首页布局中,对搜索框元素就采用了粘性布局,具体是怎么实现的呢?我们先来看一下整体效果(如下图 , 大家也可以打开饿了么微信小程序体验一把~)。
/2021/10/59014e82.gif" /2021/10/59014e82.gif" alt="page.gif
template代码:
<template> <!-- 粘性定位搜索盒子 --> <view class="search-box" :style="{top:top+'px'}"> <view class="ctn"> <view class="hx-search-box" @click="goSearch"> <view class="hx-search-text"> <uni-icons type="search" size="22" color="#666666" /> <text>鲜果大咖水果捞 20减12</text> </view> <view> <button class="search-txt">搜索</button> </view> </view> </view> </view> </template>
注意:这里给search-box盒子添加了动态属性top,这是因为在小程序端,搜索框在不同移动设备上具体父元素的距离是变化的。如何求动态的top属性值呢?
<script> export default { data() { return { //在这里给到top属性一个默认的值为0 top: 0 } }, onLoad() { // 获取手机系统信息 状态栏高度 const statusBarHeight = uni.getSystemInfoSync().statusBarHeight // 获取胶囊的位置 const menuButtonInfo = uni.getMenuButtonBoundingClientRect() //导航栏的高度 = (胶囊底部高度 - 状态栏的高度) + (胶囊顶部高度 - 状态栏内的高度) this.navBarHeight = (menuButtonInfo.bottom - info.statusBarHeight) + (menuButtonInfo.top - info.statusBarHeight) //top的值为状态栏的高度+导航栏的高度 this.top = menuButtonInfo.bottom + menuButtonInfo.top - statusBarHeight; } } </script> <style> .search-box { position: sticky; z-index: 2; </style>
/2021/10/18d1f429.png" /2021/10/18d1f429.png" alt="23.png" width="797" height="435" style="width: 797px;height: 435px
以上就是uniapp开发饿了么微信小程序首页sticky粘性定位布局的详细内容,更多请关注北冥有鱼其它相关文章!
本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。