先上个效果图

d69a7f1dcd3b4a538d609d50cecb3d53.gif

 

 顶部的搜索框是由padding撑开的和底部也是同样使用padding撑开的一个功能按钮。

中间的分类数据就是此项目的数据展示区域,他是需要配置滚动属性的,而滚动属性,往往是需要设置一个固定高度,从而使他溢出部分进行一个scroll进行滚动。

 

下面就详细解释一下动态获取高度此功能过程:

1.首先是需要先获取顶部的高度,这里呢是通过绑定ref,拿到高度(附图)

<search-bar
      ref="searchBar"
      :isShowSelect="false"
      placeholderText="请输入分类名称"
    />
    const searchBarHeight = this.$refs.searchBar.$el.offsetHeight;

2.是同样的拿到底部功能按钮区域的高度,同样使用通过绑定ref,拿到高度(附图)

      <bottom-operate-btn ref="bottomOperateBtn" text="添加分类" />
    const bottomBtnHeight = this.$refs.bottomOperateBtn.$el.offsetHeight;

3.最后,是给中间区域的标签绑定ref,操作dom元素给标签获取动态高度(注意⚠️:下方在计算高度的时候,一定一定一定要用获取到浏览器的可视化区域高度去做减法,不能直接使用100vh,否则在手机端浏览会出现问题!)

<div class="classify-layout" ref="classifyLayout">
      <div
        class="classify-content"
        v-for="item in 15"
        :key="item"
        @click="goToClassifyDetails"
      >
        <div class="classify-content-keft">
          <img class="classify-logo" src="" />
          <span class="classify-name">短T</span>
        </div>
        <span class="classify-num">共33款</span>
      </div>
      <bottom-line />
      <bottom-operate-btn ref="bottomOperateBtn" text="添加分类" />
    </div>

 

    // document.body.clientHeight // body区域内被内容撑开的距离 如果没有文档这个高度就是0
    // document.documentElement.clientHeight // 显示的是文档的区域,即使没有内容也有高度, 属于文档对象模型
    // window.innerHeight // 显示的是文档的区域,即使没有内容也有高度, 属于BOM(浏览器对象模型)    
    // 获取浏览器可视区域高度
    const height = window.innerHeight;
    this.$refs.classifyContent.style.height = `calc(${height}px - ${searchBarHeight}px - ${bottomBtnHeight}px)`;

完结~

 

总结:通过ref绑定操作dom元素,相对于直接通过document操作dom,减少了操作dom节点;动态获取高度很好的做到了适应各式各样的手机类型自行自适应!(如有不恰之处,望指明,勿喷!)

 

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐