簡體   English   中英

根據 ID 和特定屬性值向元素添加 CSS 類

[英]Add CSS class to element based on the ID and a specific attribute value

如果id具有使用jQuery的特定style屬性,我想向body添加一個新class 為什么這段代碼不起作用?

if ($('#myID').css('display') == 'none'){
  $('body').addClass('loaded');
}

先感謝您!

我找到了解決辦法。 當我不斷檢查時它會起作用,而不僅僅是一次:

function check_loader(){
      if ($('#ple-loader-wraps99').css('display') == 'none'){
        $('body').addClass('loaded');
      };};
window.setInterval(check_loader,1000);  

您可以使用MutationObserver API 監聽特定 DOM 節點上的 DOM 更改,然后觸發操作:

 const targetNode = document.getElementById('my-id'); // Specify which mutations to observe (options) const config = { attributes: true }; // Simulate the preloader action (webpage load) setTimeout(function() { document.querySelector('#my-id').style ='display: none;' }, 1000) // Callback function to execute when mutations are observed const callback = function (mutationsList, observer) { console.log(`Mutation type: ${mutationsList[0].type}`) console.log(`ID ${mutationsList[0].target.id}`); // Make the necessary changes to your target elements here document.querySelector('body').classList.add('loaded'); }; // Create an observer instance linked to the callback function const observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config);
 .loaded { background-color: crimson; }
 <div id="my-id">Loading..</div>

注意:所有代碼都是 Vanilla JS(沒有 jQuery)。

使用官方文檔中的代碼創建的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM