![](/img/trans.png)
[英]Getting class or ID name of an element based on the value of a particular attribute
[英]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.