简体   繁体   English

查找特定的CSS @keyframes规则

[英]Find specific CSS @keyframes rule

I want to adjust a specific @keyframes -rule in my CSS with JavaScript. 我想用JavaScript调整我的CSS中的特定@keyframes This all worked pretty well with the following code: 这一切都适用于以下代码:

CSS: CSS:

@-webkit-keyframes changecolor {
    0% { color: red; }
    100% { color: green; }
}
@keyframes changecolor {
    0% { color: red; }
    100% { color: green; }
}

JavaScript: JavaScript的:

function getKeyframeRule(ruleName) {
    var ss = document.styleSheets,
        rule, i, x;

    for (i = 0; i < ss.length; ++i) {
        if (ss[i].cssRules) {
            // loop through all the rules
            for (x = 0; x < ss[i].cssRules.length; ++x) {
                rule = ss[i].cssRules[x];
                if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE) && rule.name === ruleName) {
                    return rule;
                }
            }
        }
    }
    return null;
}

// find keyframes rule
var rule = getKeyframeRule("changecolor");
console.log(rule.cssText);

// adjust keyframes rule
// ...

Since Chrome 43 the browser supports unprefixed CSS animation properties. 自Chrome 43以来,浏览器支持无前缀的CSS动画属性。 But my code still returns the prefixed keyframes rule @-webkit-keyframes changecolor because it also applies to the condition if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE) && rule.name === ruleName) { . 但是我的代码仍然返回带前缀的关键帧规则@-webkit-keyframes changecolor因为它也适用于条件if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE) && rule.name === ruleName) {

What's a better way to select the keyframes rule which is actually used by the browser? 选择浏览器实际使用的关键帧规则有什么更好的方法?

Here is the full example: http://jsfiddle.net/tschortsch/zbma3bcp/2/ 以下是完整的示例: http//jsfiddle.net/tschortsch/zbma3bcp/2/

The keyframes rule used is the last to be defined. 使用的keyframes规则是最后定义的。 Therefore, you can loop from the end, instead of from the beginning: 因此,您可以从最后而不是从头开始循环:

for (x = ss[i].cssRules.length - 1; x >= 0; x--) {
    rule = ss[i].cssRules[x];
    if ((rule.type === window.CSSRule.KEYFRAMES_RULE || rule.type === window.CSSRule.WEBKIT_KEYFRAMES_RULE) && rule.name === ruleName) {
        return rule;
    }
}

See fiddle . 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM