顶部高度不固定,内容区域高度滚动的两种实现方法

197 阅读1分钟
场景描述:顶部高度不固定,内容会随着窗口的resize换行,
列表区域高度要自适应

如图所示: 1111.png

方法一:这种是通过css的flex布局实现

<div id="wrapper"> 
    <div class="header">头部</div>
    <div class="main">剩下的</div>
</div>
#wrapper { 
    width: 100%; 
    height: 100%;
    display: flex; 
    flex-direction: column; 
} 
.header { 
    width: 100%; 
    height: auto; 
    flex-shrink: 0; 
} 
.main {
    width: 100%; 
    flex: 1;// flex 1的意思就是 flex-grow 1,这里是缩写 // 
    flex-grow: 1;
    overflow-y: auto;
  }

注意事项:最外层父元素wrapper必须有设置高度

方法二:这种是js的window.resize实现动态计算高度

<div id="wrapper"> 
    <div class="header">头部高度确定</div>
    <div class="list" :style="{height:currentHeight}">滚动区域</div>
    <div class="bottom" ref="bottom">底部高度不确定 内容会换行</div>
</div>

data(){
    return {
        screenWidth: document.body.clientWidth,//必须有
        timer:null,
        currentHeight:''
    }
},
beforeDestroy (){
    this.timer = null
},
watch:{
     screenWidth (val) {
      if (!this.timer) {
         this.screenWidth = val
         this.timer = true
         setTimeout( ()=>{
          let bottomHeight = this.$refs.bottom.offsetHeight + 30
         let topHeight = 112
          this.currentHeight =  (window.innerHeight - bottomHeight - topHeight) + 'px'
          // console.log(bottomHeight,'bottomHeight') 
         this.timer = null
         }, 400)
       }
     }
 },
 created(){
    setTimeout( ()=>{
      let bottomHeight = this.$refs.bottom.offsetHeight + 30
      let topHeight = 112 //头部固定高度
      this.currentHeight =  (window.innerHeight - bottomHeight - topHeight) + 'px'
      // console.log(bottomHeight,'bottomHeight') 
      this.timer = null
    }, 400)
    
  },
  mounted(){
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
  },