MutationObserver не срабатывает при установке дисплея на none - PullRequest
0 голосов
/ 05 февраля 2020

У меня есть узел с именем 'cover', который устанавливается видимым или невидимым, когда слой ajax хочет скрыть / показать его, основываясь на том, что он является нашей завесой. Но мы хотим, чтобы наша завеса была не просто видимой или невидимой. Поэтому я написал MutationObserver, чтобы следить за изменениями и выполнять дополнительную работу. Это прекрасно работает, когда узел меняется на display: block. Он НЕ срабатывает при изменении отображения: нет.

Вы можете видеть наблюдателя ниже, и между этим и точками останова, я уверен, что он никогда не вызывается на дисплее: ничего не меняется. И да, я вижу, что изменение было внесено в список наблюдения. Это происходит как в IE, так и в Chrome.

Ожидается ли это? Я этого не ожидал. Но если так, как я могу получить это отображение: нет события?

Вызов для запуска наблюдателя:

veilObserver.observe(cover, { attributes: true, childList: false, subtree: false });

Наблюдатель:

const veilObserver = new MutationObserver(function(mutationsList, observer) {
console.log("MutationObserver enter");
var cover = document.getElementById('cover');

if(cover) {
    console.log("MutationObserver cover");
    if(cover.style.display == 'none') {
        console.log("MutationObserver closing");
        closeVeil();
    } else if(cover.style.display == 'block') {
        openVeil();
    } else {
        //this should never happen, but if it does, we want to make sure the veil is closed because we don't know whether it should be open or
        //closed and I'd rather default to open so the user isn't locked forever. 
        console.log('Mutation!!! but display not recognized: ' + cover.style.display);
        closeVeil();
    }
} else {
    console.log("MutationObserver disconnecting");
    //this implies the page lacks the required HTML.  Disconnect the observer and don't both them again.
    veilObserver.disconnect();
}

}) ;

1 Ответ

0 голосов
/ 05 февраля 2020

Скопировал это из документации и адаптировал к вашему коду.

Вы должны попробовать наблюдать родительский элемент #cover. Таким образом, будут наблюдаться любые мутации внутри этого элемента.

    // Select the node that will be observed for mutations
    const targetNode = document.getElementById(/* The parent element of #cover */);

    // Any changes inside this div will be observed.

    // Options for the observer (which mutations to observe)
    const config = { attributes: true, childList: true, subtree: true };

    // Callback function to execute when mutations are observed
    const callback = function(mutationsList, observer) {
        // Use traditional 'for loops' for IE 11
        for(let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                console.log('A child node has been added or removed.');
                // Check if the element that changed was #cover
                console.log(mutation.target.id === 'cover');

                if(mutation.target.id === 'cover') {
                  let id = mutation.target.id;
                  if(document.getElementById(`#${id}`).style.display === 'none') {
                    // Do something
                    // disconnect perhaps.
                  }
                }


            }
            else if (mutation.type === 'attributes') {
                // If the style is inline this may work too. 
                console.log('The ' + mutation.attributeName + ' attribute was modified.');
                console.log(mutation.attributeName === 'style');

                let id = mutation.target.id;

                if(document.getElementById(`#${id}`).style.display === 'none') {
                  // Do something
                  // disconnect perhaps.
                }
            }
        }
    };

    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);

    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);

    // Later, you can stop observing
    observer.disconnect();

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

...