简体   繁体   English

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

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

Take the following html:采取以下html:

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

somediv is already hidden, some javascript runs, effectively doing nothing. somediv 已经隐藏,一些 javascript 运行,实际上什么都不做。 I need code that detects when style.display has been used in javascript, regardless of if style was changed or not.我需要检测 style.display 何时在 javascript 中使用的代码,无论样式是否更改。

I've tried MutationObserver :我试过MutationObserver

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

The above only triggers if there was a style change.以上仅在样式更改时触发。 I need it to trigger regardless if there was a style change or not.无论风格是否发生变化,我都需要它来触发。

So I did come up with an answer.所以我确实想出了一个答案。 The way it works, is you grab every script tag, replace .style.display with your own function, and finally replace the DOM (which is the real trick):它的工作方式是获取每个脚本标签,用你自己的函数替换 .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>');
        }

});

Now here is my .style.display replacement function:现在这是我的 .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 is what actually changes the DOM. .replaceWith是真正改变 DOM 的东西。 The only thing this script doesn't do, is it isn't able to look through included javascript files .这个脚本唯一没有做的就是它不能查看包含的 javascript 文件 Thank you all for your comments <3.谢谢大家的意见<3。

UPDATE:更新:

When using replaceWith to add the script tag, ipad/iphone/ipod will execute the script tag a second time.使用replaceWith添加script标签时,ipad/iphone/ipod会再次执行script标签。 to prevent this double execution, you need to do this:为了防止这种双重执行,您需要这样做:

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

Your functions will be valid, but anything outside of the function will not be executed.您的函数将有效,但不会执行函数之外的任何内容。

I don't think you fully realise what you are asking for, but here is a short description of closest options I am aware of:我认为您没有完全意识到您的要求,但这里是我所知道的最接近选项的简短描述:

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

Basically, MutationObserver is the major improvement over past here that is closest to what you want and supported in modern browsers.基本上, MutationObserver是过去这里的主要改进,最接近您想要的并且在现代浏览器中支持。 But the whole point of all this is it listens to changes.但所有这一切的全部意义在于它倾听变化。

You are basically asking to detect even non-changes.您基本上要求检测甚至非更改。 I don't see you getting out of this problem other than:除了:

Writing a wrapper for the ways you use to change this in code and then instead of calling the change call the wrapper.为您用来在代码中更改它的方式编写一个包装器,然后调用包装器而不是调用更改。 Simple, easy, requires refactoring all the calls in code.简单,容易,需要重构代码中的所有调用。

Overwriting the actual functions that make a change.覆盖进行更改的实际功能。 This saves you the refactor but you are playing with fire here.这为您节省了重构,但您在这里玩火。 Rewriting a well-known function on a global level means a PERMANENT source of problems to you and all developers who work on the project.在全局层面重写一个众所周知的函数对你和所有参与该项目的开发人员来说意味着问题的永久来源。

Polling - in short calling over and over on some element to check properties.轮询- 简而言之,在某些元素上一遍又一遍地调用以检查属性。 Not only it detects changes with a lag of 0 to the polling interval it also uses resources and if you want to monitor everything you will have to write a recursion that descends through the current DOM from the top to each node and check it.它不仅检测到轮询间隔滞后为 0 的变化,它还使用资源,如果你想监视一切,你将不得不编写一个递归,从顶部到每个节点,通过当前 DOM 下降并检查它。 You are gonna kill the performance with this.你会用这个来扼杀表演。 How hard I can't tell but I suspect either polling interval will be long thus increasing the detection lag or your performance will dive down like a gray falcon.我不知道有多难,但我怀疑轮询间隔会很长从而增加检测延迟,或者您的性能会像灰色猎鹰一样下降。

I have 1 big question for you:我有一个大问题要问你:

What led you to the state where you need this?是什么让您走到了需要它的状态? You basically want the ability for a program to detect when it is using a specific part of itself (be that as it is, a core part, one implemented by the browser).您基本上希望程序能够检测到它何时使用自身的特定部分(就其本身而言,核心部分,由浏览器实现的部分)。 This sounds similar to request: hey whenever I change or not change a value in any variable in my code I should be able to react to it.这听起来类似于 request:嘿,每当我更改或不更改代码中任何变量的值时,我都应该能够对其做出反应。

I am not trying to sound like Naggin Nancy here but instead encourage you to question train of thought that led to this being something you need and figure out whether you want to sink further time into this, because I don't think you are getting that what you desire easily and I suspect it came to be due to poor design decisions in the past.我不是想在这里听起来像 Naggin Nancy,而是鼓励你质疑导致这是你需要的东西的思路,并弄清楚你是否想进一步投入时间,因为我认为你没有得到那个你很容易想要什么,我怀疑这是由于过去糟糕的设计决策。

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

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