繁体   English   中英

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

[英]Javascript detect when style.display is used regardless of style change

采取以下html:

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

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

我试过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>');

您的函数将有效,但不会执行函数之外的任何内容。

我认为您没有完全意识到您的要求,但这里是我所知道的最接近选项的简短描述:

https://blog.sessionstack.com/how-javascript-works-tracking-changes-in-the-dom-using-mutationobserver-86adc7446401

基本上, MutationObserver是过去这里的主要改进,最接近您想要的并且在现代浏览器中支持。 但所有这一切的全部意义在于它倾听变化。

您基本上要求检测甚至非更改。 除了:

为您用来在代码中更改它的方式编写一个包装器,然后调用包装器而不是调用更改。 简单,容易,需要重构代码中的所有调用。

覆盖进行更改的实际功能。 这为您节省了重构,但您在这里玩火。 在全局层面重写一个众所周知的函数对你和所有参与该项目的开发人员来说意味着问题的永久来源。

轮询- 简而言之,在某些元素上一遍又一遍地调用以检查属性。 它不仅检测到轮询间隔滞后为 0 的变化,它还使用资源,如果你想监视一切,你将不得不编写一个递归,从顶部到每个节点,通过当前 DOM 下降并检查它。 你会用这个来扼杀表演。 我不知道有多难,但我怀疑轮询间隔会很长从而增加检测延迟,或者您的性能会像灰色猎鹰一样下降。

我有一个大问题要问你:

是什么让您走到了需要它的状态? 您基本上希望程序能够检测到它何时使用自身的特定部分(就其本身而言,核心部分,由浏览器实现的部分)。 这听起来类似于 request:嘿,每当我更改或不更改代码中任何变量的值时,我都应该能够对其做出反应。

我不是想在这里听起来像 Naggin Nancy,而是鼓励你质疑导致这是你需要的东西的思路,并弄清楚你是否想进一步投入时间,因为我认为你没有得到那个你很容易想要什么,我怀疑这是由于过去糟糕的设计决策。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM