xiaohao
xiaohao

Reputation: 272

Access the keyframe of css3 animation

I've found that there is a function called WebKitCSSKeyframesRule in the window object, but it seems that executing this function leads to an error. Does anyone know how this function works? Is there a good way to modify the keyframe of css3 animation?

Upvotes: 2

Views: 901

Answers (1)

MaxArt
MaxArt

Reputation: 22647

WebKitCSSKeyframesRule isn't a function: it's a contructor that's used internally when parsing stylesheets.

To modify a @keyframes rule, you have to find it first:

var styleSheet = document.styleShees[0], keyframesRule;

for (var i = 0; i < styleSheet.cssRules.length; i++) {
    if (styleSheet.cssRules[i].type === CSSRule.WEBKIT_KEYFRAMES_RULE) {
        keyframesRule = styleSheet.cssRules[i];
        break;
    }
}
alert(keyframesRule instanceof WebKitCSSKeyframesRule); // alerts "true"

Once you have your rule, you can modify, add, delete frame rules using the rule's cssRules property and the addRule, deleteRule methods, like you usually do with common stylesheets:

for (var i = 0; i < keyframesRule.cssRules.length; i++)
    alert(keyframesRule.cssRules[i].keyText + " { "
            + keyframesRule.cssRules[i].style.cssText + " }");

That's the same as alerting keyframesRule.cssRules[i].cssText.

Obviously, this is all vendor prefixed, so for Firefox you'll have to use MozCSSKeyframesRule instead, and so on.

Upvotes: 2

Related Questions