我可以从JavaScript访问无效/自定义CSS属性的值吗? [英] Can I access the value of invalid/custom CSS properties from JavaScript?

查看:161
本文介绍了我可以从JavaScript访问无效/自定义CSS属性的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下CSS:

div {
    -my-foo: 42;
}

稍后我可以用JavaScript知道 -my-foo CSS属性适用于给定的 div

Can I later in JavaScript somehow know what the value of the -my-foo CSS property is for a given div?

推荐答案

我不认为你可以访问无效的属性名称,至少它不工作在Chrome或Firefox为我。 CSSStyleDeclaration只是跳过无效的属性。对于给定的CSS:

I don't think you can access invalid property names, at least it doesn't work in Chrome or Firefox for me. The CSSStyleDeclaration simply skips the invalid property. For the given CSS:

div {
    width: 100px;
    -my-foo: 25px;
}

style:CSSStyleDeclaration 对象只包含以下键:

0: width
cssText: "width: 100px"
length: 1

但有趣的是,这是 DOM-Level-2 Style spec 说:

虽然实现可能无法识别CSS声明块中的所有CSS属性,但预期通过CSSStyleDeclaration接口提供对样式表中所有指定属性的访问。
While an implementation may not recognize all CSS properties within a CSS declaration block, it is expected to provide access to all specified properties in the style sheet through the CSSStyleDeclaration interface.

意味着CSSStyleDeclaration对象应该在上面的示例中列出了 -my-foo 属性。也许有一些浏览器支持它。

implying that the CSSStyleDeclaration object ought to have listed the -my-foo property in the above example. Maybe there is some browser out there which supports it.

我用于测试的代码位于 http: //jsfiddle.net/q2nRJ/1/

The code I used for testing is at http://jsfiddle.net/q2nRJ/1/.

注意:您可以随时通过解析原始文本来DIY。例如:

Note: You can always DIY by parsing the raw text. For example:

document.getElementsByTagName("style")[0].innerText

但这似乎对我很多的工作,不知道你的原因,我不能说如果一个更好的替代问题存在。

but that seems like a lot of work to me, and not knowing your reasons for doing this, I can't say if a better alternate for your problem exists.

这篇关于我可以从JavaScript访问无效/自定义CSS属性的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆