我们想将作为字符串输入的CSS样式转换为JS对象。
例如。,
var input = " border:solid 1px; color:red ";
预期的JS对象:
{
border:"solid 1px",
color:"red"
}
当然,样式条目的数量是无限的,以及样式的名称(边框,颜色,字体,z-index等)。谢谢。
我们想将作为字符串输入的CSS样式转换为JS对象。
例如。,
var input = " border:solid 1px; color:red ";
预期的JS对象:
{
border:"solid 1px",
color:"red"
}
当然,样式条目的数量是无限的,以及样式的名称(边框,颜色,字体,z-index等)。谢谢。
您可以使用Javascript拆分功能: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
首先拆分字符串 ;
作为分隔符,然后为每个结果分割 :
,将物品放在物体中。
例如
var result = {},
attributes = input.split(';');
for (var i = 0; i < attributes.length; i++) {
var entry = attributes[i].split(':');
result[entry.splice(0,1)[0]] = entry.join(':');
}
一个非常简单的:
var regex = /([\w-]*)\s*:\s*([^;]*)/g;
var match, properties={};
while(match=regex.exec(cssText)) properties[match[1]] = match[2].trim();
所有的答案似乎需要大量的分裂 - 为什么不进行比赛并一次性获得所有对?
function cssSplit(str){
var O= {},
S= str.match(/([^ :;]+)/g) || [];
while(S.length){
O[S.shift()]= S.shift() || '';
}
return O;
}
在功能形式:
var styleInput = " border:solid 1px; color:red ";
var result = styleInput.split(';').reduce(function (ruleMap, ruleString) {
var rulePair = ruleString.split(':');
ruleMap[rulePair[0].trim()] = rulePair[1].trim();
return ruleMap;
}, {});
在将字符串用作对象键之前修剪字符串。
只是为了好玩和完整......
我没有检查过跨浏览器兼容性(仅在Chrome中尝试过),它有一些怪癖:
var input = "font-weight:bold; color: blue; margin: 0 15px";
var e = document.createElement("div");
e.setAttribute("style", input);
var output = {};
for (var i = 0; i < e.style.length; i++) {
var name = e.style[i];
var value = e.style.getPropertyValue(name);
output[name] = value;
}
怪癖是即使我们传入一个单一的 margin
声明,我们得到一个像这样的对象
{
color: "blue",
font-weight: "bold",
margin-bottom: "0px",
margin-left: "15px",
margin-right: "15px",
margin-top: "0px",
}
根据你所追求的目标,这可能是好事也可能是坏事。
const css2obj = css => {
const r = /(?<=^|;)\s*([^:]+)\s*:\s*([^;]+)\s*/g, o = {};
css.replace(r, (m,p,v) => o[p] = v);
return o;
}
console.log( css2obj("z-index: 4; opacity:1; transition-duration: 0.3s;") )
如果你想转换 dash-case
JS表示的CSS属性 camelCase
, 代替 p
使用 p.replace(/-(.)/g, (m,p) => p.toUpperCase())
Oldschool JS:
function cssToObj(css) {
var obj = {}, s = css.toLowerCase().replace(/-(.)/g, function (m, g) {
return g.toUpperCase();
}).replace(/;\s?$/g,"").split(/:|;/g);
for (var i = 0; i < s.length; i += 2)
obj[s[i].replace(/\s/g,"")] = s[i+1].replace(/^\s+|\s+$/g,"");
return obj;
}
console.log( cssToObj("z-index: 4; opacity:1; transition-duration: 0.3s;") );
这样的事情会让你非常接近:
var input = " border:solid 1px; color:red ";
var output = '{' + input.replace(/([\w-.]+)\s*:([^;]+);?/g, '\n $1:"$2",') + '\n}';
...转弯
" border:solid 1px; color:red "
成
{
border:"solid 1px",
color:"red ",
}
这是我将CSS字符串转换为对象的函数:
function cssConverter(style) {
var result = {},
attributes = style.split(';'),
firstIndexOfColon,
i,
key,
value;
for(i=0; i<attributes.length; i++) {
firstIndexOfColon = attributes[i].indexOf(":");
key = attributes[i].substring(0, firstIndexOfColon);
value = attributes[i].substring(firstIndexOfColon + 1);
key = key.replace(/ /g, "");
if(key.length < 1){
continue;
}
if(value[0] === " "){
value = value.substring(1);
}
if(value[value.length - 1] === " "){
value = value.substring(0, value.length - 1);
}
result[key] = value;
}
return result;
};