简单判断元素是否滚动到了底部

简单判断元素是否滚动到了底部

前置知识

先来理解DOM元素的三个属性

  • scrollTop: 元素顶部到元素可视区域顶部的像素距离(可读写)。
  • clientHeight: 元素的像素高度,包括盒子内容content和内边距padding, 不包括边框外边距和水平滚动条(只读)。
  • scrollHeight: 类似于clientHeight,但包括由于overflow属性不可见内容的高度。

三者的关系如下图所示:绿色部分是滚动元素能看到的部分,假设红色框区域是元素的总高度,部分被隐藏。
在这里插入图片描述

如何判断

MDN上有一条公式,用于判断元素是否滚动到底部:
在这里插入图片描述
结合前面的示意图可知,元素滚动到底部的条件是scrollTop + clientHeight === scrollHeight

Vue写法

以Vue举例,只需监听scroll事件获取到scrollTop, clientHeight 和 scrollHeight的值再进行判断,就能知道元素是否滚动到底部。

<template>
  <div id="app">
    <div class="scroll-view"
         ref="scrollView"
         id="scroll-view"
         @scroll="handleScroll">
      <div
          v-for="(item, index) in list"
          :key="index"
          class="list-item">
        列表项{{item}}
      </div>
    </div>
  </div>
</template>
<script>

export default {
  name: 'HelloWorld',
  data() {
    return {
      list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    };
  },
  mounted() {
    this.$nextTick(() => {
      console.log('clientHeight', this.$refs.scrollView.clientHeight)
    })
  },
  methods: {
    handleScroll(e) {
      const {scrollTop, clientHeight, scrollHeight} = e.target
      // console.log(scrollTop, clientHeight, scrollHeight)
      if (scrollTop + clientHeight === scrollHeight){
        alert('滚动到底部啦')
      }
    }
  }
}
</script>
<style scoped>
.scroll-view {
  width: 400px;
  height: 300px;
  overflow-y: scroll;
  background-color: #68b687;
}

.list-item {
  padding: 40px 0;
}

.list-item:nth-child(2n + 1){
  background-color: rgba(0, 0, 0, .2);
}

.list-item:nth-child(2n + 2){
  background-color: rgba(222, 221, 221, 0.2);
}
</style>

效果演示

在这里插入图片描述

参考

https://www.cnblogs.com/weiyf/p/8718051.html
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值