2015-09-14 30 views
-2

我已經定義了兩個<div>元素,一個在另一個之內。我聽聽<div>裏面有width:auto;。當我改變父母的寬度<div>時,我預期從突變觀察者回調的火力會發生變化,因爲目標<div>的寬度會發生變化。但沒有發生。突變Obeserver未觸發動態更改的回調

什麼問題?

// Blocker is the element that has a changing display value 
 
var blocker = document.querySelector('#blocker'); 
 
// Trigger changes the display value of blocker 
 
var trigger = document.querySelector('#trigger'); 
 
// Our mutation observer, which we attach to blocker later 
 
var observer = new MutationObserver(function(mutations) { 
 
    mutations.forEach(function(mutation) { 
 
    // Was it the style attribute that changed? (Maybe a classname or other attribute change could do this too? You might want to remove the attribute condition) Is display set to 'none'? 
 
    if (mutation.attributeName === 'style') { 
 
     alert(window.getComputedStyle(blocker).getPropertyValue('width')); 
 
    } 
 
    }); 
 
}); 
 

 
// Attach the mutation observer to blocker, and only when attribute values change 
 
observer.observe(blocker, { 
 
    attributes: true 
 
}); 
 

 
// Make trigger change the style attribute of blocker 
 
trigger.addEventListener('click', function() { 
 
    $('#d').css('width', '300px'); 
 
    //  $('#blocker').css('background-color','red'); 
 
}, false);
#d { 
 
    width: 200px; 
 
} 
 
#blocker { 
 
    width: auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div id="d"> 
 
    <div id="blocker" style="display:none">Stop!</div> 
 
</div> 
 
<div id="trigger">Show blocking element</div>

View on JSFiddle

回答

0

你正在觀察#blocker DIV是#d DIV的孩子。但點擊後,您將更改父項屬性(#d)。 MutationObserver只能觀察元素本身或元素和子樹(MDN)。所以回調不會被觸發,因爲你只是改變另一個DOM元素的屬性

+0

是的,我正在觀察#blocker。但是,攔截器中的更改將會更改子元素#d右側的寬度。 – divakar

+0

家長的變化不會導致孩子的突變觀察員發火 – Andrey

+0

那麼實現這個目標的最好方法是什麼?任何想法? – divakar