IntersectionObserver监听容器元素

IntersectionObserver是Chrome 51+已经支持的API,用来检测目标元素是否处于root容器之中。
之前我们在做懒加载的时候,通常都是监听浏览器scroll事件,然后根据元素位置是否处于可视窗口来做的,这种方式有个弊端就是,页面在监听scroll滚动的时候会导致页面加载不流畅。
使用IntersectionObserverAPI就可以避免这种情况,达到平滑加载的目的,并且可以根据threshold来定义回掉函数在什么时候触发,更加的简单准确。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
    .container{
        width: 1100px;
        margin: 0 auto;
    }
    .test_model{
        height: 300px;
        width: 300px;
        margin-top: 1200px;
        background-color: red;
        margin-bottom: 600px;
    }
    </style>
</head>
<body>
    <div class="container">
        <div class="test_model" id="model"></div>
    </div>
    <script type="text/javascript">
        window.onload = function(){
            var obs = new IntersectionObserver((changes)=>{
                changes.forEach(change => console.log(change.intersectionRatio.toFixed(2)))
            },{
                threshold: [0, 0.25, 0.5, 0.75, 1]
            });
            obs.observe(document.getElementById('model'));
        };
    </script>
</body>
</html>

IntersectionObserver有observe,unobserve,disconnect等三个方法,分别指绑定观察对象、停止观测、关闭观察器。
IntersectionObserver(callbakc,opts)接受两个参数,第一个参数为回调函数,在检测目标根据opts里面的threshold内容来触发。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值