简体   繁体   English

监听HTML元素,不带setInterval

[英]Listen for HTML elements, without setInterval

I am wondering if it's possible to listen for elements in DOM without using setInterval like I am doing it right now: 我想知道是否可以像现在正在使用setInterval一样监听DOM中的元素:

 var interval = setInterval(() => { var div = document.querySelector('.test'); if (div != null) { clearInterval(interval); console.log(div); } }, 1000); 

My problem is that this specific div is loaded in DOM after 10-12 min randomly. 我的问题是,此特定div会在10-12分钟后随机加载到DOM中。 And I think setInterval I just an ugly solution for this. 而且我认为setInterval我只是一个丑陋的解决方案。 So my question is, is it even possible to listen for new divs in DOM, without using interval? 所以我的问题是,是否有可能在不使用间隔的情况下监听DOM中的新div?

This seems like a good job for Mutation Observer . 对于Mutation Observer来说,这似乎是一项不错的工作。 It will observe a static parent on your DOM and alert you of any changes to the structure. 它将在您的DOM上观察到一个静态父对象,并警告您结构的任何更改。 You can listen for a child node with a class of test to be added. 您可以侦听带有要添加的test类的子节点。 For example: 例如:

 // this setTimeout is only to show this example working. it is not needed setTimeout(() => { let aDiv = document.createElement('div'); aDiv.className = 'test'; document.getElementById('parent').appendChild(aDiv); }, 3000); let targetNode = document.getElementById('parent'); let config = { attributes: false, childList: true, subtree: true }; // Callback function to execute when mutations are observed let callback = function(mutationsList, observer) { for (let mutation of mutationsList) { if (mutation.type == 'childList') { for (let node of mutation.addedNodes) { if (node.className === "test") { console.log("a node with class test was added!"); // stop observing observer.disconnect(); } } } } }; // Create an observer instance linked to the callback function let observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config); 
 <div id="parent"> </div> 

This can be achieved using CSS keyframe animations. 这可以使用CSS关键帧动画来实现。

Javascript: 使用Javascript:

(function(){

    var count = 1,
    event = function(event){
        if (event.animationName == 'nodeInserted')
     event.target.textContent = 'Element ' + count++ + ' has been parsed!';
    }

    document.addEventListener('animationstart', event, false);
    document.addEventListener('MSAnimationStart', event, false);
    document.addEventListener('webkitAnimationStart', event, false);

    // this is test code which imitates your div being created
    // after a delay
    setTimeout(function(){
        var div = document.createElement('div');
        div.setAttribute('class', 'some-control');

        document.getElementById('test').appendChild(div)
    }, 2000);

})();

CSS: CSS:

    @keyframes nodeInserted {  
        from {  
            outline-color: #fff; 
        }
        to {  
            outline-color: #000;
        } 
    }

    @-moz-keyframes nodeInserted {  
        from {  
            outline-color: #fff; 
        }
        to {  
            outline-color: #000;
        }  
    }

    @-webkit-keyframes nodeInserted {  
        from {  
            outline-color: #fff; 
        }
        to {  
            outline-color: #000;
        }  
    }

    @-ms-keyframes nodeInserted {  
        from {  
            outline-color: #fff; 
        }
        to {  
            outline-color: #000;
        } 
     }

    @-o-keyframes nodeInserted {  
        from {  
            outline-color: #fff; 
        }
        to {  
            outline-color: #000;
        }  
    } 

    div.some-control {
        padding: 50px;
        background: #FF6A6A;
        animation-duration: 0.01s;
        -o-animation-duration: 0.01s;
        -ms-animation-duration: 0.01s;
        -moz-animation-duration: 0.01s;
        -webkit-animation-duration: 0.01s;
        animation-name: nodeInserted;
        -o-animation-name: nodeInserted;
        -ms-animation-name: nodeInserted;        
        -moz-animation-name: nodeInserted;
        -webkit-animation-name: nodeInserted;
    }

    div.some-control div.some-control {
        background: #87CEFF;
    }

Credit to: http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/ 致谢: http : //www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM