IntersectionObserver实现无限滚动,MutationObserver监听dom元素

IntersectionObserver 接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        
       p{
        margin: 100px 0;
       }
 
    </style>
</head>
<body  style="min-height: 1000px;">
    <div id="bod">
        <p>---</p>
        <p>---</p>
    </div>
 
    <div id="footer" style="height: 150px;background-color: rebeccapurple;">底部</div>
    <script>
       let cont = 1;
       let obs = new IntersectionObserver(
        function(changes) { //changes 是所有监听的元素集合
            添加40个元素之后,停止监听
            if(cont>=40) {obs.unobserve(footer)}
            // 避免页面加载就触发一次
            if (changes[0].intersectionRatio <= 0) return;
            for(let i=0;i<10;i++){
                let dom = document.createElement("p");
                dom.innerHTML = 'son'+cont++
                document.querySelector('#bod').appendChild(dom)
            
            // 监听的元素出现75%的时候在触发回调
        },{threshold:0.75})
 
       obs.observe(footer)
    //    可以同时监听多个元素
    //    例如
    //    obs.observe(footer1)
    //    obs.observe(footer2)
    </script>
 
</body>
</html>
MutationObserver:可以监听元素发生的变化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
        <div id="tar"> 123 </div>
        <script>
            let obs = new MutationObserver((e)=>{
                console.log(e);
            })
 
            // 监听tar元素的子节点是否有变化,更多的监听可以在第二个参数里面配置
            // 观察器所能观察的DOM变动类型有以下几种:
            // childList:子节点的变动。
            // attributes:属性的变动。
            // characterData:节点内容或节点文本的变动。
            // subtree:所有后代节点的变动。
            obs.observe(tar,{childList:true})
 
            document.onclick = function(){
                let dom = document.createElement("p");
                dom.innerHTML = 'son'
                tar.appendChild(dom)
                tar.style.width = "200px"
            }
        </script>
</body>
</html>

  

posted @   吴百万  阅读(265)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示