Opposite of jQuery.camelCase for CSS property names

拜拜、爱过 提交于 2019-12-08 07:19:24

问题


jQuery.camelCase is used to convert dashed CSS properties to camelcased CSSOM(? or DOM?) properties.

I'd like to do the opposite to dynamically create a CSS transition value.

I don't want to use the all keyword for this. I'd like to make it possible to not force the coder to only use background-color instead of backgroundColor.

Is this possible (maybe via jQuery) or will it take lots of code for cross browser support?

Edit:

$("#example").css("transition-property", "backgroundColor") // Fail

I don't want to do exactly the same as in my example but this shows the problem.

I'm trying to iterate through an object that contains css properties and values to set the objects keys as transition-properties. E.g. { backgroundColor: "red" } should set background-color as transition-property instead of backgroundColor.


回答1:


A simple function to do the job is:

function deCase(s) {
    return s.replace(/[A-Z]/g, function(a) {return '-' + a.toLowerCase()});
}

alert(deCase('scrollbarDarkShadowColor')); // scrollbar-dark-shadow-color

There are likely many other ways.

Also, you can do camelCase using:

function camelCase(s) {
    return s.replace(/-(.)/g, function(a, $1){return $1.toUpperCase();});
}



回答2:


I found a solution from jQuery.transit.js:

function uncamel(str) {
    return str.replace(/([A-Z])/g, function(letter) { return '-' + letter.toLowerCase(); });
}

Any better (more documented/tested) solutions are welcome!



来源:https://stackoverflow.com/questions/16640527/opposite-of-jquery-camelcase-for-css-property-names

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