IntersectionObserver是Chrome 51+已经支持的API,用来检测目标元素是否处于root容器之中。
以前咱们在作懒加载的时候,一般都是监听浏览器scroll事件,而后根据元素位置是否处于可视窗口来作的,这种方式有个弊端就是,页面在监听scroll滚动的时候会致使页面加载不流畅。
使用IntersectionObserverAPI就能够避免这种状况,达到平滑加载的目的,而且能够根据threshold来定义回掉函数在何时触发,更加的简单准确。javascript
<!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内容来触发。css