无论样式更改如何,Javascript 都会检测何时使用 style.display

标签 javascript

采用以下html:

<div id="somediv" style="display:none;"></div>
<script>
    document.getElementById("somediv").style.display = 'none';
</script>

somediv 已经隐藏,一些 javascript 运行,实际上什么都不做。我需要代码来检测何时在 javascript 中使用了 style.display,无论样式是否已更改。

我试过了 MutationObserver :

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        alert(mutationRecord.target.id);
    });
});
observer.observe(document.getElementById("somediv"), { attributes : true, attributeFilter : ['style'] });

以上仅在样式发生变化时触发。 无论是否有样式更改,我都需要它来触发。

最佳答案

所以我确实想出了一个答案。它的工作方式是抓取每个脚本标签,将 .style.display 替换为您自己的函数,最后替换 DOM(这才是真正的技巧):

//loop through <script> tags
$('script').each(function(){
        var scripthtml = $(this).html();
        if (scripthtml.indexOf('style.display') != -1){
            scripthtml = scripthtml.replace(/.style.display = 'none'/g, ".customdisplay('none')");
            scripthtml = scripthtml.replace(/.style.display = "none"/g, '.customdisplay("none")');
            scripthtml = scripthtml.replace(/.style.display ='none'/g, ".customdisplay('none')");
            scripthtml = scripthtml.replace(/.style.display ="none"/g, '.customdisplay("none")');
            scripthtml = scripthtml.replace(/.style.display='none'/g, ".customdisplay('none')");
            scripthtml = scripthtml.replace(/.style.display="none"/g, '.customdisplay("none")');
            $(this).replaceWith('<script>' + scripthtml + '</script>');
        }

});

现在这是我的 .style.display 替换函数:

HTMLElement.prototype.customdisplay = function(showhide){
    //insert whatever code you want to execute
    this.style.display = showhide;
    alert('Success!  .style.display has been detected!');
};

.replaceWith 是真正改变 DOM 的东西。此脚本唯一不能做的事情是无法查看包含的 javascript 文件。谢谢大家的评论 <3.

更新:

当使用replaceWith添加script标签时,ipad/iphone/ipod会再次执行script标签。要防止这种双重执行,您需要这样做:

$(this).replaceWith('<script>if (1==0){' + scripthtml + '}</script>');

你的函数将是有效的,但函数之外的任何东西都不会被执行。

关于无论样式更改如何,Javascript 都会检测何时使用 style.display,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53641404/

相关文章:

javascript - 传单显示所有制造商的所有弹出窗口并保留在 map 中

javascript - JavaScript 中动态加载的问题

javascript - 浏览器忽略 Javascript

javascript - 如何正确地在函数中编写一个使流程满意的条件?

javascript - 无法从 javascript/nodejs 中的全局变量检索数据

javascript - 模拟固定的侧边栏模板问题

javascript - 在 Javascript 中处理多维 HTML 数组

javascript - 读取前设置未定义的 javascript 属性

javascript - 如何通过ajax发送base64图像

javascript - 为什么我的调整剪辑图像大小的脚本不起作用?