开发者

CSS Style property names -- going from the regular version to the JS property camelCase version and vice versa

Does there exist a provision for obtaining the corresponding names?

A function I'm writing has to both set the style via element.style[propnameCamelCase] and retrieve the existing rendered value via document.defaultView.getComputedStyle(element,'').getPropertyValue(propname-regular), and I can hardly justify having to pass two separate but semantically identical arguments to this function.

I know that for most of them it's a fairly straightforward transcription between camelCase and hyphen-delimited with the same words, so I can use regexes to convert them. But maybe there are a few that are not like this?

Off the top of my head I'm having a hard time figuring out how to deal with the capitalized letters for camel case with regular expressions.

edit: Ah, I could use a function for regex replace, each time I see a hyphen, conver开发者_开发知识库t next letter to upper case.


So you're basically reinventing jQuery.css(). Maybe a look at how jQuery solved the camelCase problem might help: https://github.com/jquery/jquery/blob/master/src/core.js#L600


I was about to ask question about the same thing (and I intended to name it "Translate css names to\from javascript counterparts"). Somehow I ended up writing my own solution.

function cssNameToJsName(name)
{
    var split = name.split("-");
    var output = "";
    for(var i = 0; i < split.length; i++)
    {
        if (i > 0 && split[i].length > 0 && !(i == 1 && split[i] == "ms"))
        {
            split[i] = split[i].substr(0, 1).toUpperCase() + split[i].substr(1);
        }
        output += split[i];
    }
    return output;
}

function jsNameToCssName(name)
{
    return name.replace(/([A-Z])/g, "-$1").toLowerCase();
}


I'd like to mention that CSSStyleDeclaration.style.setProperty accepts css/hyphen type property names without conversion, as documented here

Try this hyphenated property, for example:

document.body.style.setProperty("background-color", "red");

You can also do this:

document.body.style["background-color"] = "silver";

These approaches - if you can use them - may be simpler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜