IntersectionObserver--采集多元素曝光时间完整demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://cdn-h5.iauto360.cn/css/reset.min.css"> <style> html,body{ font-size: 100px; overflow-x: hidden; } #info { height: 800px; width: 100%; font-size:20px; } #t1,#t2,#t3 { width: 100px; height: 100px; background: red; margin-right: 20px; font-size: 22px; } #t1,#t2{ float: left; } #t3{ margin-top: 140px; background: #000; color:#fff; } </style> <script> //->REM ~function () { var desW = 750, winW = document.documentElement.clientWidth || document.body.clientWidth; if (winW > desW) { return; } document.documentElement.style.fontSize = winW / desW * 100 + 'px'; }(); </script> <script src="https://cdn.bootcdn.net/ajax/libs/babel-polyfill/7.10.1/polyfill.min.js"></script> </head> <body> <div id="info">IntersectionObserver--采集多元素曝光时间-demo</div> <div id="t1">t1</div> <div id="t2">t2</div> <div id="t3">t3</div> <script> var tdata = {};//元素集数据 let observer = new IntersectionObserver((entries) => { initTdata(tdata,entries); // console.log("tdata:::",tdata) entries.forEach((entry,index) => { // console.log(entry.target.getAttribute('id')+"====================="); var tg = entry.target.getAttribute('id'); // console.log("tg:",tg) if (!entry.isIntersecting) { entry.isIntersecting = true if(tdata[tg].flag == 0){ tdata[tg].end_time = entry.time; let tt = (tdata[tg].end_time - tdata[tg].start_time)/1000; tdata[tg].duration = tdata[tg].duration + tt; }; tdata[tg].flag = 0; } else { entry.isIntersecting = false; tdata[tg].start_time = entry.time; } // console.log(entry.target.getAttribute('id')+"====================="); }) console.log("曝光元素数据集:",JSON.stringify(tdata)); }, { root: null // null 的时候可以省略 }) function initTdata(tdata,entries){ if(Object.keys(tdata).length>0) return; for(var i=0; i < entries.length;i++){ let tg = entries[i].target.getAttribute('id'); tdata[tg] = { flag:1, start_time:0, end_time:0, duration:0 } } } observer.observe(t1) observer.observe(t2) observer.observe(t3) </script> </body> </html>