vue js 监听页面滚动触底 && 监听iframe滚动及触底 && 带你搞清 offsetHeight,scrollTop,scrollHeight区别

想要监听页面滚动是否触底,你要先搞清 offsetHeight,scrollTop,scrollHeight区别,以及如何让应用,话不多说上代码💁🏻

offsetHeight: 它是包括padding、border、水平滚动条,但不包括margin的元素的高度。

⚠️:对于行内元素这个属性值一直是0,单位px,是只读元素。

scrollTop:表示在有滚动条时,滚动条向下滚动的距离也就是元素顶部被遮住部分的高度即“卷”起来的高度。

⚠️:在无滚动条时scrollTop==0恒成立,单位px,可读可设置。例如:“回滚到顶部”就可以用它来设置。

scrollHeight:当子元素比父元素高的时候,父元素不想被子元素撑高,于是出现了滚动条,在滚动的过程中子元素有部分会被隐藏掉,scrollHeight是 父元素高度offsetHeight + “卷”起来的高度 scrollTop,也可以理解为是子元素的offsetHeight值。



在了解了这三个属性的含义之后 理解触底就很简单了 其实就是 offsetHeight(显示区域高度) + scrollTop(卷起来的高度) - scrollHeight (子元素自身高度) >= -1 的时候就代表页面已经滑到底了~

接下来会有两种监听触底的案例:

1.div元素内内容触底

2.iframe内内容触底

 

我们先来看下第一种:div元素内内容触底

<div class="wrapper">
    <div class="content">
          独立寒秋,湘江北去,橘子洲头。
          看万山红遍,层林尽染;漫江碧透,百舸争流。
          鹰击长空,鱼翔浅底,万类霜天竞自由。
          怅寥廓,问苍茫大地,谁主沉浮?
          携来百侣曾游。忆往昔峥嵘岁月稠。
          恰同学少年,风华正茂;书生意气,挥斥方遒。
          ...
    <div>
</div>


<style>
.wrapper {
    margin: 0 auto;
    background: #fff;
    height: 100vh;
    overflow: hidden;
}
.wrapper-content {
    height: 100vh;
    overflow-y: scroll;
}
<style>


<script>
    export default {
        created() {
            this.$nextTick(() => {
                const el = document.querySelector('.content');
                const offsetHeight = el.offsetHeight;
                el.onscroll = () => {
                    const scrollTop = el.scrollTop;        
                    const scrollHeight = el.scrollHeight;
                    if (offsetHeight + scrollTop - scrollHeight >= -1) {
                        console.log("到达底部了")
                    }
                };
            });
        },
    }
<script>

 

第二种就是监听iframe内的滚动是否触底

<style>
.wrapper {
    margin: 0 auto;
    background: #fff;
    height: 100vh;
    overflow: hidden;
}
.wrapper-content {
    height: 100vh;
    overflow-y: scroll;
}
<style>


<div class="wrapper">
    <iframe
      id="iframepage"
      src="XXX.html"
      frameborder="0"
      width="90%"
      class="content"
    ></iframe>
<div>


<script>
    export default {
        created() {
            this.$nextTick(() => { // iframe包裹
                const frameWindow = document.getElementById('iframepage').contentWindow;
                $(frameWindow).scroll(function () {
                    const ifm =frameWindow.document.documentElement;
                    const scrollHeight = ifm.scrollHeight;
                    const offsetHeight = frameWidow.innerHeight;
                    const scrollTop = frameWidow.document.body.scrollTop;
                    if (offsetHeight + scrollTop - scrollHeight >= -1) {
                        console.log("到底啦~")
                    }
                });
            });
        },
    }
<script>

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值