基本上,我正在检测隐藏广告的 CSS 的存在,如果我找到它,我想显示一条小消息。但是,我发现即使在加载 dom 时执行所有这些代码 ($(function(){})
) 它仍然只有在我设置超时时才有效,即使超时为零。有谁知道为什么会这样(在 Mac 上的 Chrome 中测试过)
function detect(callback){
for (var x = 0; x < document.styleSheets.length; x++) {
var rules = document.styleSheets[x].cssRules;
for (var i = 0; i < rules.length; i++) {
if(rules[i].style.display == 'none' && [].slice.call(rules[i].selectorText.match(/ads/ig), 0).length > 10)
{
return callback()
}
}
}
}
// fails, the plugins css hasn't been applied yet
detect(function(){
$("#sorryYouDontLikeOurAds").show()
})
// but this works even with a timeout of zero
setTimeout(function(){
detect(function(){
$("#sorryYouDontLikeOurAds").show()
})
}, 0);
最佳答案
嗯,setTimeout
不能将 0ms 的值作为有效延迟。大多数浏览器会将延迟“限制”到某个最小值。我认为大约需要 4-10 毫秒,具体取决于浏览器。可能发生的情况是插件代码在您的代码运行后的某个时刻在 $.ready 循环上执行。因此,您必须对其设置某种超时以使其“等待”足够长的时间,直到插件加载,这才有意义。
您可以阅读更多有关 setTimeout
工作原理的信息 here .
关于javascript - 为什么我在调用 setTimeout 之前无法检测到 Chrome 插件的样式更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5606334/