簡體   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