当前位置: 首页 > 未分类>阅读正文

javascript监听元素变化

2022.6.20 朱丰华 2488 次 留下评论 1396字

使用 js 的 MutationObserver 类,能监视对 DOM 树所做更改。

例如,监听元素属性变化:

<div id="div1">111111111</div>
<button onclick="handleClick()">OK</button>



<script type="text/javascript" charset="utf-8">

    const div1 = document.querySelector('#div1');
    
    const observe = new MutationObserver((mutations) => {
        console.log('hhhh', mutations)
    }).observe(div1, {
        attributes: true
    })

    function handleClick() {
        div1.setAttribute('style', 'color: red')
        div1.setAttribute('data-name', 'abc')
    }
    
</script>

例如,监听元素样式变化:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<style>
    #box2,#box1,#box3{
        width:100px;
        height: 100px;
        background: yellow;
        margin-left: 50px;
        margin-top:10px;
    }
</style>
<div>
   <div id="box1">
   </div>
    <div id="box2">
    </div>
    <div id="box3">
        <button id="btn">
            点击改变宽高
        </button>
    </div>
</div>
<script>
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    var box1=document.getElementById("box1"); //对象{}
    var box2=document.getElementById("box2"); //对象{}
    var btn=document.getElementById("btn");
    let width=100;
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type == "attributes") {
                console.log("attributes changed", mutation);
                box2.style.width=mutation.target.style.width
            }
        });
    });
    observer.observe(box1, {
        attributes: true, //configure it to listen to attribute changes,
        attributeFilter: ['style']
    });
    btn.onclick=function(){
        width+=10;
        box1.style.width = width+"px";
    };
</script>
</body>
</html>
 

本篇完,还有疑问?留下评论吧

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注