使用translate撑开滚动容器高度

250 阅读1分钟

想要撑开滚动容器有哪些方法?

  • 滚动容器内容添加一个元素,让元素的高度超出滚动条
  • 【文章主角】滚动容器设置为相对定位,再在滚动容器内容添加一个元素(绝对定位),设置元素的translate,让translateY值大于滚动容器的高度,就能撑开这个滚动容器了
<!--

@author: pan
@createDate: 2022-11-24 09:54
-->
<script setup lang="ts"></script>

<template>
  <div>
    <div class="container">
      <div class="fitHeight"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  position: relative;
  border: 1px solid #333;
  overflow-x: hidden;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  width: 300px;
  height: 500px;
}
.fitHeight {
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  // 注意至少要设置1px的宽度,不然translate达不到撑开高度的效果
  width: 1px;
  height: 1px;
  transform: translate(0, 700px);
}
</style>