我有一个使用 Canvas 的 JS 库,它需要从 CSS 类中获取颜色。库使用的类是预先确定的,但哪些样式表(可能有很多)不是预先确定的。
像这样的类:
.a_preset_class {
margin: 10pt;
color: rgba(216,34,21,0.5);
}
我希望能够写出这样的东西:
context.strokeStyle = getClassColor("a_preset_class");
并将 context.strokeStyle
设置为 "rgba(216,34,21,0.5);"
明显的方法是遍历 document.styleSheets
,但我希望有一种我不知道的不那么激烈的方法。
最佳答案
如果您能够在您的站点中使用 Dojo,您可以使用 dojox.data.CssRuleStore 为您的所有 CSS 规则创建一个可搜索的存储区。然后使用标准的 fetch() 方法搜索商店,使用样式规则的“选择器”属性作为搜索词。例如,
ruleStore = dojox.data.CssRuleStore(); // make it a global if it's not part of a widget
// so that it's accessible by the other methods
// below when calling ruleStore.getValue()
var rulesFound = [];
// When querying the store, you can either do an exact match search such as ".myClass",
// or do a wildcard-based search such as ".myClass*" (find all rules that start with
// ".myClass", "*.myClass*" (all rules containing ".myClass" somewhere in the selector),
// "?someValue" (any rules that have an arbitrary first character, followed by
// "someRule"), etc.
var queryObj = {"selector": ".a_preset_class"};
var checkEmpty = function(count, request) {
if (count < 1)
// do your empty response logic here
};
var processRule = function(item, request) {
rulesFound.push(ruleStore.getValue(item, "style"); // Add the item's CSSStyleDeclaration object with all assigned values to the results array
};
ruleStore.fetch({query: queryObj, onBegin: checkEmpty, onItem: processRule});
以这段代码为起点,您可以创建一个函数,将所需的搜索词作为参数,将其传递给查询,然后返回找到的 CSS 规则数组。然后您可以在调用函数后迭代响应数组,并进行所需的任何更改。
关于javascript - 通过 JS 从多个样式表中获取 CSS 类内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8004359/