uni-ui的抽屉组件为什么无法在页面底部固定?

皇甫雨涵 阅读 87

我在用uni-ui的抽屉组件做侧边栏时发现,设置position: fixed后抽屉还是会随页面滚动,但文档里说默认支持固定定位啊

我尝试这样写的:


<template>
  <view class="container">
    <uni-drawer :visible="true" mode="right" :styles="{position: 'fixed'}">
      <!-- 内容 -->
    </uni-drawer>
    <!-- 主页内容 -->
    <scroll-view scroll-y style="height: 100vh">
      <view v-for="i in 50" :key="i">列表项{{i}}</view>
    </scroll-view>
  </view>
</template>

设置了fixed后抽屉虽然在初始位置固定了,但滚动到页面中部时抽屉会突然跳到可视区右侧边缘,而不是固定在屏幕右边缘

我来解答 赞 7 收藏
二维码
手机扫码查看
2 条解答
设计师文明
这个问题我踩过坑,uni-ui 的 uni-drawer 组件底层是用 模拟的,它默认是 absolute 定位,不是 fixed,你传 {position: 'fixed'} 只是改了外层样式,但组件内部逻辑没变,滚动时会出问题。

关键点在于:uni-drawer 在 H5 和小程序里会监听滚动事件动态调整 top/left,导致 fixed 失效。你看到的“突然跳到右侧边缘”就是它在算滚动偏移量时出错了。

解决方案有两个:

第一个,绕过组件自带定位逻辑,直接用原生 写个抽屉,用 fixed 定位,自己控制显示隐藏,简单又稳:

<template>
<view class="container">
<view v-if="drawerVisible" class="drawer" @tap="drawerVisible = false"></view>
<view class="drawer-content" :class="{ 'drawer-open': drawerVisible }">
<!-- 内容 -->
</view>

<scroll-view scroll-y style="height: 100vh">
<view v-for="i in 50" :key="i">列表项{{i}}</view>
</scroll-view>
</view>
</template>

<style>
.container {
position: relative;
height: 100vh;
}

.drawer {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.4);
z-index: 999;
}

.drawer-content {
position: fixed;
top: 0;
right: -750rpx; /* 默认隐藏 */
bottom: 0;
width: 750rpx;
background: #fff;
transition: right 0.3s ease;
z-index: 1000;
}

.drawer-content.drawer-open {
right: 0;
}
</style>


第二个,如果非要用 uni-drawer,那就别传 position,改用 width + zIndex,然后外层包一层 fixed 容器:

<view class="drawer-wrapper">
<uni-drawer :visible="true" mode="right" :styles="{width: '750rpx', zIndex: 9999}">
<!-- 内容 -->
</uni-drawer>
</view>


.drawer-wrapper {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: 750rpx;
z-index: 9999;
}


我建议用第一个,自己写更可控,uni-ui 的 drawer 在不同端表现不一致,线上项目容易翻车。
点赞 4
2026-02-24 14:00
❤晨硕
❤晨硕 Lv1
这个问题我之前也遇到过,确实是有点坑。虽然文档说抽屉组件默认支持固定定位,但实际使用的时候,它的行为会受到外层容器的影响,特别是当页面有滚动区域时。

你的问题主要是因为 uni-drawer 的样式作用域和外层的 scroll-view 冲突了。position: fixed 在这种情况下不会按预期工作,因为它其实被限制在了 scroll-view 的内部,而不是相对于整个窗口定位。

解决办法是把 uni-drawer 提到 scroll-view 外面,让它不被滚动区域影响。另外,确保你给 uni-drawer 设置的样式是基于全局窗口的,而不是局部的某个容器。

改一下代码,大概像这样:

<template>
<view class="container">
<!-- 主页内容 -->
<scroll-view scroll-y style="height: 100vh">
<view v-for="i in 50" :key="i">列表项{{i}}</view>
</scroll-view>

<!-- 抽屉放到 scroll-view 外面 -->
<uni-drawer :visible="true" mode="right" :styles="drawerStyles">
<!-- 内容 -->
</uni-drawer>
</view>
</template>

<script>
export default {
data() {
return {
drawerStyles: {
position: 'fixed',
top: '0',
right: '0',
bottom: '0',
width: '240px', // 根据需要调整宽度
zIndex: 999 // 确保层级足够高
}
};
}
};
</script>


这里我把 uni-drawer 放到了 scroll-view 外面,这样它就不会受滚动的影响了。另外,drawerStyles 中明确设置了 toprightbottom,让抽屉组件完全基于窗口定位。

如果还是有问题,可以检查一下项目中是否有其他全局样式影响了 position: fixed 的表现,比如 transform 或者 overflow 的设置。

希望能帮到你!
点赞 3
2026-02-14 01:00