長連接-常見於移動端向下滑動加載更多(load more)

移動端加載更多使用demo

  • 長連接

MDN - IntersectionObserver:異步觀察目標元素與其祖先元素或頂級文檔視窗(viewport)交叉狀態的方法
Document.createDocumentFragment():常用於創建空白文檔片段,然後將這個片段添加到dom結構中

  • demo
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0">
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }

        body {
            margin: 8px;
        }

        .container > li {
            font-size: 20vw;
            display: flex;
            justify-content: center;
            height: 100px;
            background: lightgray;
            margin: 8px;
            border: 1px solid hotpink;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="scrollerHeader" id="first-item">first</div>

    <ol class="container" id="container">
    </ol>
    <div class="scrollerFooter" id="last-item">加載更多</div>
</div>

</body>

<script>
    const firstId = 'first-item';
    const lastId = 'last-item';
    const listSize = 10;
    let firstIndex = 0;
    const container = document.getElementById("container");
    const list = document.querySelectorAll("#container li")
    const firstDom = document.getElementById("first-item")
    const lastDom = document.getElementById("last-item")


    let ob = new IntersectionObserver((entries) => {
        if (entries[0].intersectionRatio <= 0) return;
        entries.forEach(item => {
            if (item.target.id === firstId) {
                //向上滑動
                console.log("first id");
                scrollFun('up')
            } else if (item.target.id === lastId) {
                //向下滑動
                console.log("last id");
                scrollFun('down')
            }
        })
    })

    ob.observe(firstDom)
    ob.observe(lastDom)

    function scrollFun(direction) {
        if (direction === 'up') {
            //刪除自身
            // container.parentNode.removeChild(container);
            // render();
        }
        if (direction === 'down') {
            render()
        }
    }

    function render() {
        let fragment = document.createDocumentFragment();
        for (let i = 0; i < listSize; i++) {
            let dom = document.createElement('li');
            dom.innerHTML = firstIndex + i;
            fragment.appendChild(dom);
        }
        firstIndex = firstIndex + listSize;
        container.appendChild(fragment)
    }
    render(firstIndex);
</script>
</html>

更多可查看鏈接:IntersectionObserver API 使用教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章