问题描述
我需要检查CSS规则是否存在,因为如果不包括CSS文件,我想发出一些警告。
这是最好的方法?
我可以通过 window.document.styleSheets.cssRules
过滤,浏览器这是(加上我注意到Stack Overflow对象为 styleSheet [0]
)为空。
也希望将依赖关系保持最小。
有一个简单的方法来做到这一点吗?
编辑:如果没有,跨浏览器的关注点是检查 window.document.styleSheets
?。它类似于@Smamatti和@ jfriend00的答案,但更多的fleshed。我真的希望有一种方法可以直接测试规则,但是很好。
CSS:
.my-css-loaded-marker {
z-index:-98256; / *只是一个随机数字* /
}
JS:
$(function(){//必须在jq ready或$('body')上运行可能不存在
var dummyElement = $('< p>')
.hide()。css({height:0,width:0})
.addClass(my-css-loaded-marker)
.appendTo(body); //因为某些原因,在firefox上无效this
if(dummyElement.css(z-index)!= -98256&& &&& console.error){
console.error(找不到my-app.css样式,应用程序需要加载my-app.css才能正常工作);
}
dummyElement.remove();
});
I need to check if a CSS rule exists because I want to issue some warnings if a CSS file is not included.
What is the best way of doing this?
I could filter through window.document.styleSheets.cssRules
, but I'm not sure how cross-browser this is (plus I notice on Stack Overflow that object is null for styleSheet[0]
).
I would also like to keep dependencies to a minimum.
Is there a straightforward way to do this? Do I just have to create matching elements and test the effects?
Edit: If not, what are the cross-browser concerns of checking window.document.styleSheets
?
Here is what I got that works. It's similar to the answers by @Smamatti and @jfriend00 but more fleshed out. I really wish there was a way to test for rules directly but oh well.
CSS:
.my-css-loaded-marker {
z-index: -98256; /*just a random number*/
}
JS:
$(function () { //Must run on jq ready or $('body') might not exist
var dummyElement = $('<p>')
.hide().css({height: 0, width: 0})
.addClass("my-css-loaded-marker")
.appendTo("body"); //Works without this on firefox for some reason
if (dummyElement.css("z-index") != -98256 && console && console.error) {
console.error("Could not find my-app.css styles. Application requires my-app.css to be loaded in order to function properly");
}
dummyElement.remove();
});
这篇关于如何检查是否存在css规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!