【问题标题】:Adding or removing a class to an element dynamically using Mutation Observer使用 Mutation Observer 向元素动态添加或删除类
【发布时间】:2019-10-21 15:23:43
【问题描述】:

我想在弹出模式时从元素中删除一个类但是当我在网上搜索时,我发现 DOMNodeInserted 并且它一直在工作,直到它上线并且我得到的错误是 DOMNodeInserted 已被弃用。
我不断遇到的错误 enter image description here

代码在下面工作,但已被弃用。

    $(document).on('DOMNodeInserted', function(e) {
            if ( $("body").hasClass('modal-open') ) {
                $(".hide-search").hide();  
                // $(".nav-menu").addClass("border-0");
            } else if ($("body").hasClass('modal-open') === false){
                $(".hide-search").show(); 
                // $(".nav-menu").removeClass("border-0");
            }
        });

我想实现的新代码,但我不知道如何去做。

let body = document.querySelector('body');
let observer = new MutationObserver(mutationRecords => {
            console.log(mutationRecords); // console.log(the changes)

            // observe everything except attributes
            observer.observe(body, {
            childList: true, // observe direct children
            subtree: true, // and lower descendants too
            characterDataOldValue: true // pass old data to callback
            });
             });
            }
            } 

【问题讨论】:

    标签: javascript jquery dom mutation-observers


    【解决方案1】:
    • observe() 应该在回调之外
    • 您只需要观察class 属性,没有其他任何东西,因此不需要极其昂贵的subtree:true
    • class 可能包含其他内容,因此您需要忽略不相关的更改
    new MutationObserver((mutations, observer) => {
      const oldState = mutations[0].oldValue.split(/\s+/).includes('modal-open');
      const newState = document.body.classList.contains('modal-open');
      if (oldState === newState) return;
      if (newState) {
        $('.hide-search').hide();
      } else {
        $('.hide-search').show();
      }
    }).observe(document.body, {
      attributes: true,
      attributeFilter: ['class'],
      attributeOldValue: true,
    });
    

    【讨论】:

    • 刚刚签到,谢谢。我可以用下面的代码解决这个问题
    【解决方案2】:

    我能够通过这个解决方案解决上述问题

     function myFunction(x) {
                if (x.matches) {
                var body = $("body");
                var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.attributeName === "class") {
                    var attributeValue = $(mutation.target).prop(mutation.attributeName);
                    console.log("Class attribute changed to:", attributeValue);
                    if(attributeValue == "ng-scope modal-open") {
                        $(".input-group").addClass("removeDisplay");  
                        $(".nav-menu").addClass("hide-nav-menu");
                    } else {
                        $(".input-group").removeClass("removeDisplay");  
                        $(".nav-menu").removeClass("hide-nav-menu");
                    }
                    }
                });
                });
                observer.observe(body[0], {
                attributes: true
                });
                }
                } 
                // Wow It's working.
                var x = window.matchMedia("(max-width: 1240px)")
                myFunction(x) 
                x.addListener(myFunction)
    
    

    首先我使用匹配媒体来检查屏幕是否小于 1240 像素大小,然后我使用突变以及检查属性类是否存在,然后基于此执行一些特定操作。

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2017-07-19
      • 2019-12-29
      • 2016-01-28
      • 2015-04-20
      相关资源
      最近更新 更多