Iterating through CSS styles - style naming inconsistency

五迷三道 提交于 2019-12-24 14:13:56

问题


I'm trying to iterate through CSS styles. For example I get a style like this:

document.styleSheets[0].cssRules[10].style

That returns a CSSStyleRule which is an object with both integer and string keys.

The integer and .length keys can be used to iterate through the property assignments in the style, and each one gives the name of the property, for example:

document.styleSheets[0].cssRules[10].style[0] == "max-height"

The string keys give access to the actual actual text for the style like this:

document.styleSheets[0].cssRules[10].style["maxHeight"] == "100px"

So in theory it is easy to iterate through all the properties. But notice the maddening change from max-height to maxHeight! How can I deal with this? How do I even know what this mapping is? Do I just have to write a function that converts every -a to A and so on?


回答1:


I ended up using this function to change the case:

function camelCaseCssName(str) {
    var ret = "";
    for (var i = 0; i < str.length; ++i) {
        if (str[i] == '-') {
            if (i < str.length - 1) {
                ret += str[i+1].toUpperCase();
                ++i;
            }
        } else {
            ret += str[i];
        }           
    }
    return ret;
}

The link Bhojendra posted also contains this version which I haven't tested, but it is a lot shorter:

styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
  return letter.toUpperCase();
});


来源:https://stackoverflow.com/questions/28194166/iterating-through-css-styles-style-naming-inconsistency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!