如何检查CSS规则是否存在

发布于 2024-12-13 07:25:03 字数 384 浏览 0 评论 0原文

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

这样做的最佳方法是什么?

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

我还想将依赖性保持在最低限度。

有没有一种简单的方法可以做到这一点?我只需要创建匹配的元素并测试效果吗?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

橙幽之幻 2024-12-20 07:25:03

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

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

CSS 文件:

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

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;
}
檐上三寸雪 2024-12-20 07:25:03

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

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

#testObject {position: absolute;}

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


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

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

这里的要点是,如果您想查看是否包含外部样式表,则必须选择可以查找的有关该样式表的内容(文件名或其中的某些规则或它引起的某些效果)。

I test for proper CSS installation using javascript.

I have a CSS rule in my stylesheet that sets a particular id to 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.


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

无人问我粥可暖 2024-12-20 07:25:03

这是我得到的有效方法。它与@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();
});

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();
});
流云如水 2024-12-20 07:25:03

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

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

如果返回结果,则意味着存在一个链接元素,其 href 以“my-app.css”结尾。

接下来使用此函数来验证您所依赖的元素上的特定 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;
}

这样的

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

随机样式或

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

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

$('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"

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

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")
疯了 2024-12-20 07:25:03

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

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文