JavaScript/jQuery : How to trigger an event when "display: none" is removed?

标签 javascript jquery mutation-observers

如果之前有人回答过这个问题,我深表歉意,我无法使用搜索找到它。

我必须标记 4 个元素以在它们未隐藏时触发事件(“显示:无”被删除)。我认为 mutationObserver 是正确的方法,但我无法过滤到我需要的事件。

谁有这方面的经验?

编辑:不幸的是,我们无法访问实际取消隐藏元素的脚本。它们由另一个团队拥有和保护。我们唯一可以关注的是元素何时取消隐藏。

我试图找出如何根据我的需要编辑它。

    // 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 );

最佳答案

我们来了

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 });

基本上我们得到了样式属性中设置的默认值(如果有的话)——它存储在previousValue中;然后我们留下代码,但我们在循环中做了一些不同。首先,我们检查目标中的样式是否已更改。然后我们在目标的样式属性中获取当前显示值。下一步是比较这些值。如果 previousValue 为“none”而现在为其他值,则表示 display: none 未设置。但是,您必须注意,它只监听此特定更改。如果您不需要收听“none”,则可以省略它。

您可以在您的代码中使用它 - 我并不是故意编写您的整个代码,所以请随意在目标上添加您的事件监听器。

关于JavaScript/jQuery : How to trigger an event when "display: none" is removed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37168158/

相关文章:

jquery - jQuery 选择器可以与 DOM 突变观察器一起使用吗?

javascript - 你如何让突变观察者检测文本区域的值变化?

javascript - 从 python 中调用 Javascript 函数,在 html 中调用 Flask 函数

javascript - 错误 : response is not defined

javascript - Ajax和PHP session 问题,简单测试不起作用

javascript - 试图将我的 div 的高度设置为窗口高度的 80%

php - 需要一些解决办法。 jquery 中的点击事件中未调用 Javascript 函数

javascript - jQuery加载函数页面加载问题

javascript - 如何使用 .load() 加载脚本

javascript - MutationObserver 和 querySelectorAll