关于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 @ 2023-12-25 10:53  一剑天门  阅读(188)  评论(0编辑  收藏  举报