QQ小程序里怎么让自定义组件在页面滚动时固定在顶部?

一慧玲 阅读 29

我在做一个QQ小程序页面,顶部有个自定义导航组件custom-navbar。想让它在页面滚动时固定在顶部,但试了position: fixed一直没效果。页面结构是这样的:


<custom-navbar></custom-navbar>
<scroll-view scroll-y class="content">
  <!-- 长列表内容 -->
</scroll-view>

样式里给导航组件加了:


custom-navbar {
  position: fixed;
  top: 0;
  width: 100%;
  background: #fff;
}

但滚动时组件直接消失不见了,页面内容像是覆盖在固定组件上面。用微信开发者工具调试发现元素确实定位在最外层了,但就是显示不出来…是不是QQ小程序对fixed有特殊限制?

我来解答 赞 4 收藏
二维码
手机扫码查看
1 条解答
怡博 ☘︎
QQ小程序里 fixed 定位在自定义组件上确实有坑,你遇到的问题很常见。核心原因是 scroll-view 的滚动不会触发页面级的滚动事件,所以 fixed 元素没法正常定位,而且容易被层级覆盖。

正确的做法是把 custom-navbar 提到 scroll-view 外面,并且用 sticky 布局代替 fixed。你可以这样改结构:

<view class="container">
<custom-navbar class="sticky-nav"></custom-navbar>
<scroll-view scroll-y class="content">
<!-- 长列表内容 -->
</scroll-view>
</view>


然后样式改成:

.container {
display: flex;
flex-direction: column;
height: 100vh;
}

.sticky-nav {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 999;
background: #fff;
}

.content {
flex: 1;
overflow-y: auto;
}


这样做有几个关键点:要用 -webkit-sticky 兼容小程序内核;z-index 要提上去避免被盖住;外层容器控制高度,让 scroll-view 不撑出页面。

如果你非得用 fixed,那必须把 custom-navbar 放到页面根节点下,比如通过插槽或动态插入到 page-wraper 最外层,否则 fixed 会相对于错误的包含块定位。但强烈建议用 sticky,更稳定,也不用做额外的层级校验和兼容处理。
点赞 4
2026-02-10 19:23