如何检查是否存在css规则

时间:2021-09-14 05:04:56

I need to check if a CSS rule exists because I want to issue some warnings if a CSS file is not included.

我需要检查是否存在CSS规则,因为如果不包含CSS文件,我想发出一些警告。

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]).

我可以通过window.document.styleSheets.cssRules进行过滤,但我不确定这是什么跨浏览器(另外我注意到Stack Overflow,对象为styleSheet [0]为null)。

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?

编辑:如果没有,检查window.document.styleSheets的跨浏览器问题是什么?

5 个解决方案

#1


9  

I don't know if this is an option for you, but if it's a single file you want to check, then you can write your error message and toggle the style to hide it in that file.

我不知道这是否适合您,但如果您要检查的是单个文件,则可以编写错误消息并切换样式以将其隐藏在该文件中。

<span class="include_error">Error: CSS was not included!</span>

CSS file:

.include_error {
    display: none;
    visibility: hidden;
}

#2


4  

I test for proper CSS installation using javascript.

我使用javascript测试正确的CSS安装。

I have a CSS rule in my stylesheet that sets a particular id to position: absolute.

我的样式表中有一个CSS规则,它将特定的id设置为position:absolute。

#testObject {position: absolute;}

I then programmatically create a temporary div with visibility: hidden with that ID and get the computed style position. If it's not absolute, then the desired CSS is not installed.

然后,我以编程方式创建一个具有可见性的临时div:使用该ID隐藏并获取计算出的样式位置。如果它不是绝对的,那么就不会安装所需的CSS。


If you can't put your own rule in the style sheet, then you can identify one or more rules that you think are representative of the stylesheet and not likely to change and design a temporary object that should get those rules and test for their existence that way.

如果您不能将自己的规则放在样式表中,那么您可以确定一个或多个您认为代表样式表的规则,并且不太可能更改和设计一个临时对象,该对象应该获取这些规则并测试它们的存在那样。

Or, lastly, you could try to enumerate all the external style sheets and look for a particular filename that is included.

或者,最后,您可以尝试枚举所有外部样式表并查找包含的特定文件名。

The point here is that if you want to see if an external style sheet is included, you have to pick something about that style sheet that you can look for (filename or some rule in it or some effect it causes).

这里的要点是,如果您想查看是否包含外部样式表,您必须选择一些您可以查找的样式表(文件名或其中的某些规则或其导致的某些效果)。

#3


3  

I would use a css selector like this from within your jquery widget.

我会在你的jquery小部件中使用这样的css选择器。

$('link[href$="my-app.css"]')

If you get a result back it means there is a link element that has a href ending with "my-app.css"

如果你得到一个结果,那就意味着有一个链接元素,其href以“my-app.css”结尾

Next use this function to validate a specific css property on an element you are depending on. I would suggest something specific to you styles like the width of a container rather something random like -9999 zindex

接下来使用此函数来验证您所依赖的元素的特定css属性。我会建议一些特定于你的样式,如容器的宽度,而不是像-9999 zindex那样的随机

var getStyle = function(el, styleProp) {
    var x = !!el.nodeType ? el : document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
    return y;
}

Like this

getStyle($('#stats-container')[0], "width") 

or

getStyle("stats-container", "width")

#4


2  

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.

这就是我所得到的。它类似于@Smamatti和@jfriend00的答案,但更加充实。我真的希望有一种方法可以直接测试规则但是哦。

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();
});

#5


0  

If you are worried about not being able to edit other people's stylesheets, you can proxy them through a stylesheet of your own, using import

如果您担心无法编辑其他人的样式表,您可以使用导入通过自己的样式表代理它们

@import url('http://his-stylesheet.css');
.hideErrorMessage{ ... }

This is enough if you just want to know if your code is trying to load the stylesheet but won't help if you need to know if the foreign stylesheet was then loaded correctly.

如果您只是想知道代码是否正在尝试加载样式表,但是如果您需要知道是否正确加载了外部样式表,这就足够了。

#1


9  

I don't know if this is an option for you, but if it's a single file you want to check, then you can write your error message and toggle the style to hide it in that file.

我不知道这是否适合您,但如果您要检查的是单个文件,则可以编写错误消息并切换样式以将其隐藏在该文件中。

<span class="include_error">Error: CSS was not included!</span>

CSS file:

.include_error {
    display: none;
    visibility: hidden;
}

#2


4  

I test for proper CSS installation using javascript.

我使用javascript测试正确的CSS安装。

I have a CSS rule in my stylesheet that sets a particular id to position: absolute.

我的样式表中有一个CSS规则,它将特定的id设置为position:absolute。

#testObject {position: absolute;}

I then programmatically create a temporary div with visibility: hidden with that ID and get the computed style position. If it's not absolute, then the desired CSS is not installed.

然后,我以编程方式创建一个具有可见性的临时div:使用该ID隐藏并获取计算出的样式位置。如果它不是绝对的,那么就不会安装所需的CSS。


If you can't put your own rule in the style sheet, then you can identify one or more rules that you think are representative of the stylesheet and not likely to change and design a temporary object that should get those rules and test for their existence that way.

如果您不能将自己的规则放在样式表中,那么您可以确定一个或多个您认为代表样式表的规则,并且不太可能更改和设计一个临时对象,该对象应该获取这些规则并测试它们的存在那样。

Or, lastly, you could try to enumerate all the external style sheets and look for a particular filename that is included.

或者,最后,您可以尝试枚举所有外部样式表并查找包含的特定文件名。

The point here is that if you want to see if an external style sheet is included, you have to pick something about that style sheet that you can look for (filename or some rule in it or some effect it causes).

这里的要点是,如果您想查看是否包含外部样式表,您必须选择一些您可以查找的样式表(文件名或其中的某些规则或其导致的某些效果)。

#3


3  

I would use a css selector like this from within your jquery widget.

我会在你的jquery小部件中使用这样的css选择器。

$('link[href$="my-app.css"]')

If you get a result back it means there is a link element that has a href ending with "my-app.css"

如果你得到一个结果,那就意味着有一个链接元素,其href以“my-app.css”结尾

Next use this function to validate a specific css property on an element you are depending on. I would suggest something specific to you styles like the width of a container rather something random like -9999 zindex

接下来使用此函数来验证您所依赖的元素的特定css属性。我会建议一些特定于你的样式,如容器的宽度,而不是像-9999 zindex那样的随机

var getStyle = function(el, styleProp) {
    var x = !!el.nodeType ? el : document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
    return y;
}

Like this

getStyle($('#stats-container')[0], "width") 

or

getStyle("stats-container", "width")

#4


2  

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.

这就是我所得到的。它类似于@Smamatti和@jfriend00的答案,但更加充实。我真的希望有一种方法可以直接测试规则但是哦。

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();
});

#5


0  

If you are worried about not being able to edit other people's stylesheets, you can proxy them through a stylesheet of your own, using import

如果您担心无法编辑其他人的样式表,您可以使用导入通过自己的样式表代理它们

@import url('http://his-stylesheet.css');
.hideErrorMessage{ ... }

This is enough if you just want to know if your code is trying to load the stylesheet but won't help if you need to know if the foreign stylesheet was then loaded correctly.

如果您只是想知道代码是否正在尝试加载样式表,但是如果您需要知道是否正确加载了外部样式表,这就足够了。