uniapp搜索框吸顶
uniapp实现搜索框吸顶效果
在uniapp中实现搜索框吸顶效果,可以通过以下几种方式实现:
使用CSS的position: sticky属性
.search-box {
position: sticky;
top: 0;
z-index: 999;
background-color: #ffffff;
}
这种方法简单高效,适用于大多数场景。注意需要设置z-index确保搜索框位于其他元素上方,同时设置background-color防止内容穿透。
监听页面滚动事件

onPageScroll(e) {
if (e.scrollTop > 200) { // 200为触发吸顶的滚动阈值
this.isFixed = true
} else {
this.isFixed = false
}
}
在模板中使用动态class绑定:
<view :class="['search-box', isFixed ? 'fixed' : '']"></view>
对应CSS:

.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
}
使用uniapp的scroll-view组件
<scroll-view scroll-y class="scroll-view" @scroll="handleScroll">
<view class="search-box" :style="{position: isFixed ? 'fixed' : 'static'}"></view>
<!-- 其他内容 -->
</scroll-view>
注意事项
- 在iOS设备上,position: sticky可能存在兼容性问题,建议增加-webkit-sticky前缀
- 吸顶时需要考虑状态栏高度,避免被遮挡
- 在NVUE环境下需要使用专有的sticky属性实现吸顶效果
完整示例代码
<template>
<view>
<view class="search-box" :class="{'fixed': isFixed}">
<input type="text" placeholder="搜索内容" />
</view>
<view class="content">
<!-- 页面内容 -->
</view>
</view>
</template>
<script>
export default {
data() {
return {
isFixed: false
}
},
onPageScroll(e) {
this.isFixed = e.scrollTop > 0
}
}
</script>
<style>
.search-box {
height: 100rpx;
background: #fff;
display: flex;
align-items: center;
padding: 0 30rpx;
}
.search-box.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}
.content {
padding-top: 100rpx; /* 防止内容被遮挡 */
}
</style>






