js监听div下的iframe标签

这里只是抛砖引玉,简单的使用了 MutationObserver 有兴趣的可以深入研究,还有很多可拓展的地方

html
<div class="a">
  <iframe class="b" src="http://baidu.laosiji.com" frameborder="0"></iframe>
</div>
css
 .a {width: 500px;height: 500px;background: blue;}
 .b {width: 50%; height: 50%;}
js

这里引用了jQuery

let a = $('.c'),b = $('.d');
//点击div使iframe消失
a.on('click', function (e) {
    setTimeout(() => {
        b.remove()
    }, 2 * 1000);
})
//调用监听方法,该方法可以抽离成一个单独的js
observe(a[0],callback,'IFRAME');
function callback(){
    console.log('6666')
}
/**
 * 监听元素下子元素的移除
 * @param {*} targetNode 要监听的元素,例如$('.a')[0]
 * @param {*} func 要执行的方法
 * @param {*} childAttrVal 子节点的nodeName值,例如:IFRAME
 */
function observe(targetNode, func, childAttrVal) {
    if (!func || typeof func != 'function') return new Error('func must be function');
    const mutationObserver = new MutationObserver(callback);
    mutationObserver.observe(targetNode, {
        childList: true
    });
    function callback(mutations) {
        for (let mutation of mutations) {
            let type = mutation.type;
            switch (type) {
                case "childList":
                    // console.log("A child node has been added or removed.");
                    //remove
                    if (mutation.removedNodes.length > 0) {
                        // console.log("A child node has been removed.", mutation.removedNodes);
                        checkout(mutation.removedNodes)
                    }
                    break;
                default:
                    break;
            }
        } 
    }
    function checkout(nodeArr) {
        f: for (let node of nodeArr) {
            if (node['nodeName'] && node['nodeName'] === childAttrVal) {
                func()
                break f;
            }
        }
    }
}

或者你还有更好的方法,可以留言讨论一波

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。