h5 和 小程序吸顶

uniapp展示在浏览器上

思路:

发现直接设置sticky不管用

通过监听滚动事件,在到达指定高度的时候进行样式的更换

通过getBoundingClientRect().top获取距离顶部的高度

// h5
<view class="mt-12rpx mx--32rpx" id="prideTabFixed">
    <view searchColor :class="titleFixed == true ? 'fixed' : ''">
        <wd-search
            placeholder="输入关键词搜索"
            placeholder-left
            custom-class="search-custom"
        />
    </view>
</view>
 // js
const titleFixed = ref(false)

// 滚动监听,头部固定
function handleScroll() {
  const offTop = document.getElementById('prideTabFixed').getBoundingClientRect().top
  if (offTop > 44) {
    titleFixed.value = false
  } else {
    titleFixed.value = true
  }
}
onMounted(async () => {
  window.addEventListener('scroll', handleScroll)
})

// 在组件卸载时移除滚动事件监听器
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

// css
.fixed {
  position: fixed;
  padding-top: 0;
  top: 44px; /* 根据需要调整 */
  left: 0;
  right: 0;
  z-index: 100; /* 确保元素在其他内容之上 */
  background-image: linear-gradient(to bottom, rgb(247, 251, 255), rgb(255, 255, 255));
}

但是发现小程序没有监听事件,于是更改,使用了wot-design uni组件库,<wd-sticky>

将被吸顶组件放进里面

<wd-sticky>
    <wd-search
        placeholder="输入关键词搜索"
        placeholder-left
        custom-class="search-custom"
    />
</wd-sticky>

发现会更改输入框的样式,于是

:deep(.search-custom) {
  width: 100vw;
  background: transparent !important;
}
:deep(.wd-sticky__container) {
  background-image: linear-gradient(to bottom, rgb(247, 251, 255), rgb(255, 255, 255));
}

定义宽度和背景色

结果,适配h5和小程序端:

小小记录下本文:

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值