Uniapp 微信小程序布局:固定头部和底部,中间内容自适应高度并滚动
要实现固定高度头部和底部,中间内容自适应高度并可滚动的布局,可以使用以下方案:
方案一:Flex 布局(推荐)
<template>
<view class="page-container">
<!-- 固定头部 -->
<view class="header">
头部内容
</view>
<!-- 中间可滚动内容 -->
<scroll-view class="content" scroll-y>
<view class="content-inner">
<!-- 这里放你的主要内容 -->
<view v-for="item in 50" :key="item">
内容行 {{item}}
</view>
</view>
</scroll-view>
<!-- 固定底部 -->
<view class="footer">
<input class="input" placeholder="请输入内容" />
</view>
</view>
</template>
<style>
.page-container {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.header {
height: 80rpx; /* 头部固定高度 */
background: #f7f7f7;
display: flex;
align-items: center;
padding: 0 20rpx;
/* 可根据需要添加其他样式 */
}
.content {
flex: 1; /* 占据剩余空间 */
overflow: hidden; /* 重要 */
}
.content-inner {
min-height: 100%; /* 确保内容足够时能撑开 */
padding: 20rpx;
box-sizing: border-box;
}
.footer {
height: 100rpx; /* 底部固定高度 */
background: #fff;
border-top: 1rpx solid #eee;
padding: 10rpx 20rpx;
box-sizing: border-box;
}
.input {
width: 100%;
height: 80rpx;
border: 1rpx solid #ddd;
border-radius: 8rpx;
padding: 0 20rpx;
box-sizing: border-box;
}
</style>
方案二:绝对定位布局
<template>
<view class="page-container">
<!-- 固定头部 -->
<view class="header">
头部内容
</view>
<!-- 中间可滚动内容 -->
<scroll-view class="content" scroll-y>
<view class="content-inner">
<!-- 这里放你的主要内容 -->
<view v-for="item in 50" :key="item">
内容行 {{item}}
</view>
</view>
</scroll-view>
<!-- 固定底部 -->
<view class="footer">
<input class="input" placeholder="请输入内容" />
</view>
</view>
</template>
<style>
.page-container {
position: relative;
height: 100vh;
overflow: hidden;
}
.header {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 80rpx;
background: #f7f7f7;
}
.content {
position: absolute;
top: 80rpx;
bottom: 100rpx;
left: 0;
right: 0;
overflow: hidden;
}
.footer {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 100rpx;
background: #fff;
border-top: 1rpx solid #eee;
}
</style>
注意事项
-
单位使用:建议使用
rpx
单位以保持各设备上的比例一致 -
滚动条问题:
- 确保
scroll-view
设置了scroll-y
属性 scroll-view
的父容器必须有明确的高度限制
- 确保
-
键盘弹出处理:
- 在微信小程序中,底部输入框可能会被键盘顶起,可以添加以下处理:
onLoad() { // 监听键盘高度变化 uni.onKeyboardHeightChange(res => { this.keyboardHeight = res.height }) }
然后动态调整底部位置
-
兼容性问题:
- 不同平台对
scroll-view
的实现可能有差异,需要测试 - iOS 和 Android 的滚动行为可能不同
- 不同平台对
-
性能优化:
- 如果中间内容很多,考虑使用虚拟列表优化性能
- 避免在
scroll-view
中使用过多的复杂布局
这两种方案都能实现固定头尾、中间内容自适应的布局,Flex 方案更现代且易于维护,而绝对定位方案兼容性更好。根据项目需求选择合适的方案即可。