uni-app/微信小程序:scroll-view纵向滚动高度自适应flex布局填充剩余高度

文档

  • uni-app文档:https://uniapp.dcloud.net.cn/component/scroll-view.html

使用竖向滚动时,需要给 一个固定高度,通过 css 设置 height

  • 微信文档:https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html

使用竖向滚动时,需要给scroll-view一个固定高度,通过 WXSS 设置 height

所以,给scroll-view设置一个固定高度就可以了

方案1:js计算高度

实现原理:

通过js获取设备高度和外层父元素位置信息,动态计算出剩余高度,也就是scroll-view的高度

// 获取总高度
let screenHeight = uni.getSystemInfoSync().windowHeight;

// 布局位置信息
const query = uni.createSelectorQuery().in(this)
    query
      .select('#scroll-view')
      .boundingClientRect((data) => {
    
    
        // @ts-ignore
        console.log('得到布局位置信息' + JSON.stringify(data))
        // @ts-ignore
        this.height = `height:${
      
      data.height}px;`

      })
      .exec()
<scroll-view   
        v-if="height"
        :style="height"
        bindscrolltolower="scrolltolower" 
        scroll-y
>
</scroll-view>

js的方案有一个弊端,我实际获取布局信息的时候,并没有获取到元素的布局信息,而是获取到了整屏幕的高度

方案2:使用flex布局

该方案和小程序无关,是css的知识

使用flex纵向布局,让scroll-view占满剩余高度

布局示例

<view class="main">
    <view class="title"></view>

    <scroll-view
          scroll-top="scrollTop"
          scroll-y="true"
          class="scroll-view"
          @scrolltolower="handleScrollToLower"
        >
        </scroll-view>
</view>
.main {
    
    
    height: 100%;
    display:flex;
    flex-direction: column; // 竖向排列
}

.title{
    
    
    height: 100rpx;
}

.scroll-view {
    
    
    flex: 1;    // 撑满剩余高度
    height: 0;  // 关键属性,否则scroll-view不生效
}

关键属性是height: 0,如果没有该属性,高度会溢出,不会出现滚动效果

还有一个注意的点,要一直向上检查父元素的高度都是height: 100%;

参考

猜你喜欢

转载自blog.csdn.net/mouday/article/details/129715805