1. 程式人生 > 實用技巧 >IntersectionObserver API js懶載入實現方法

IntersectionObserver API js懶載入實現方法

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <title></title>
    <style>
        #content {
            width: 100vw;
            height: 100vh;
        }

        #info {
            position: fixed;
            top: 
0; } #target { width: 100px; height: 100px; background: red; } </style> </head> <body> <div id="info">我藏在頁面底部,請向下滾動</div> <div id="content"></div> <div class="test">adsfasfd</div> <div id="target"></div> <div id="h" style="height:1000px;"></div> <div class="test">adsfasfd</div> </body> <!-- --> <script type="text/javascript"> function
query(selector) { return Array.from(document.querySelectorAll(selector)); } let observer = new IntersectionObserver(function (entries) { entries.forEach(function (element, index) { // console.log(observer.takeRecords()); if (element.isIntersecting) { info.textContent
= "我出來了"; } else { info.textContent = "我藏在頁面底部,請向下滾動" } }); }, { root: null, threshold: [0, 1] }) query(document.querySelectorAll('.test').forEach((item) => { observer.observe(item); })) // observer.observe(document.querySelectorAll('.test')[0]) </script> </html>