[英]Add CSS class to element based on the ID and a specific attribute value
I want to add a new class
to body
if an id
has a specific style
attribute using jQuery
.如果
id
具有使用jQuery
的特定style
属性,我想向body
添加一个新class
。 Why is this code not working?为什么这段代码不起作用?
if ($('#myID').css('display') == 'none'){
$('body').addClass('loaded');
}
Thank you in advance!先感谢您!
I found a solution.我找到了解决办法。 It works when I constantly check and not only once:
当我不断检查时它会起作用,而不仅仅是一次:
function check_loader(){
if ($('#ple-loader-wraps99').css('display') == 'none'){
$('body').addClass('loaded');
};};
window.setInterval(check_loader,1000);
You can listen for DOM changes on a specific DOM node using the MutationObserver
API, then trigger an action:您可以使用
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>
Note: All code is Vanilla JS (no jQuery).注意:所有代码都是 Vanilla JS(没有 jQuery)。
Example created using code from the official documentation使用官方文档中的代码创建的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.