关于uniapp设置头部固定,内容区域滚动,不同手机显示表现不一致的问题

问题

若固定了头部元素区域高度,比如固定的rpx,vh等,在其他手机中可能出现部分空白,导致界面不协调。我的解决方案是自动计算出头部区域元素的高度,让内容区域自动设置外边距

方案

使用了 unaipp提供的 uni.createSelectorQuery() 方法来获取头部区域的高度。首先,通过 ref="header" 将头部区域标记为 header,然后使用 uni.createSelectorQuery() 来获取其高度信息。获取到高度后,将其设置到 headerHeight 变量中,并通过 :style 绑定到内容区域的 margin-top 上。

这样,在页面加载后,头部区域的高度会自动应用到内容区域的 margin-top 上,实现头部固定且内容区域自适应的效果。

复制代码
<template>
  <view>
    <view class="header" ref="header">
      <!-- 这里放置头部内容 -->
    </view>
    <view class="content" :style="{ marginTop: headerHeight + 'px' }">
      <!-- 这里放置内容 -->
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      headerHeight: 0,
    };
  },
  mounted() {
    this.setHeaderHeight();
  },
  methods: {
    // 获取头部高度,设置内容区域的 margin-top
    setHeaderHeight() {
      const header = this.$refs.header;
      if (header) {
        uni.createSelectorQuery()
          .in(this)
          .select('.header')
          .boundingClientRect((rect) => {
            if (rect) {
              this.headerHeight = rect.height;
            }
          })
          .exec();
      }
    },
  },
};
</script>

<style>
/* 其他样式 */
</style>
复制代码

 

posted @   一剑天门  阅读(780)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2020-12-25 JSONP跨域提交请求
2018-12-25 配置完IDEA开发lua后用idea竟然打不开lua的文件。
2018-12-25 IDEA指定.class文件输出位置

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示