开发者

getComputedStyle object contains methods?

I have set up a demo here: http://jsbin.com/evifeb/

This is more of me thinking out loud than a proper question but..

Why do browsers insert style rules directly into the computed styles object along side methods and reserved words? It just makes it difficult to parse.. For example, you may notice in my demo that I'm filtering out everything but strings and numbers.. this is to weed out the functions that are in the same scope. Although, that is not 100% accurate because the length property value is a number.. Why not have a prototype function like "getAllStyles" that returns an object of styles without the nonsense?

OKAY so I am aware of "getPropertyValue" but that is only useful if you want a specified style rule.. So I guess what I'm trying to say is: A) Is there a proper method 开发者_如何学运维of returning such an object that is cross browser safe? and B) If not, are there any other properties (not in the css spec) besides length that need weeding out?

Thanks so much for the help. I'm ready to pull out my teeth.


It sounds like your for loops need a healthy dose of Object.hasOwnProperty.

Using a hasOwnProperty() filter will, by and large, solve the problem, but it fixes the symptoms, not the cause. The cause is that your code uses a for...in loop to iterate over an array. Don't do this.

Use for...in to iterate over objects, and use for to iterate over arrays.


One last thing: getComputedStyle() returns a (read-only) instance of CSSStyleDeclaration. Use the provided API and things are straightforward:

for (var i=0; i<computedStyles.length; i++)
{        
    cssProperty = computedStyles[i];
    cssValue = computedStyles.getPropertyValue(cssProperty);
    // snip...
}

Demo: http://jsbin.com/owenij/2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜