Nat*_*ugh 3 javascript jquery mutation-observers
如果以前回答过这个问题,我很抱歉,我无法通过搜索找到它.
我必须标记4个元素,以便在它们被取消隐藏时触发事件("display:none"被删除).我认为mutObserver是正确的方法,但我很难过滤到我需要的事件.
有没有经验呢?
编辑:不幸的是,我们无法访问实际取消隐藏元素的脚本.他们由另一个团队拥有和保护.我们唯一可以关键的是当元素被取消隐藏时.
我试图弄清楚如何根据我的需要编辑它.
// 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' && window.getComputedStyle( blocker ).getPropertyValue( 'display' ) !== 'none'
){
alert( '#blocker\'s style just changed, and its display value is no longer \'none\'' );
}
} );
} );
// 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(){
blocker.removeAttribute( 'style' );
}, false );
Run Code Online (Sandbox Code Playgroud)
开始了
var blocker = document.querySelector('#blocker');
var previousValue = blocker.style.display;
var observer = new MutationObserver( function(mutations){
mutations.forEach( function(mutation) {
if (mutation.attributeName !== 'style') return;
var currentValue = mutation.target.style.display;
if (currentValue !== previousValue) {
if (previousValue === "none" && currentValue !== "none") {
console.log("display none has just been removed!");
}
previousValue = mutation.target.style.display;
}
});
});
observer.observe(blocker, { attributes: true });
Run Code Online (Sandbox Code Playgroud)
基本上我们得到了style属性中设置的默认值(如果有的话) - 这个存储在previousValue; 然后我们保留代码,但是我们在循环中做了一些区别.首先,我们检查目标中的样式是否已更改.然后我们在目标的样式属性中获取当前显示值.下一步是比较这些值.如果previousValue为"none",现在它是其他东西,这意味着显示:none未设置.但是,您必须注意,它仅侦听此特定更改.如果您不需要听"无",那么您可以省略它.
您可以在代码中使用它 - 我没有故意编写您的整个代码,因此请随意在目标上添加您的事件监听器.
| 归档时间: |
|
| 查看次数: |
6594 次 |
| 最近记录: |