本文介绍了Javascript/将CSS样式字符串转换为JS对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们想将以字符串形式输入的CSS样式转换为JS对象.
We'd like to convert a CSS style entered as string into a JS object.
例如
var input = " border:solid 1px; color:red ";
预期的JS对象:
{
border:"solid 1px",
color:"red"
}
当然,样式条目的数目以及样式的名称(边框,颜色,字体,z-index等)是不受限制的.谢谢.
Of course the number of style entries is unlimited as well as the names of style (border, color, font, z-index, etc...). Thx.
推荐答案
您可以使用JavaScript拆分功能: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
You could use the Javascript split function: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
首先用;
作为分隔符分割字符串,然后对于每个用:
分割的结果,将项目随心放置在对象中.
First split the string with ;
as the separator, and then for each result split with :
, placing the items in an object as you go.
例如
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(':');
}
这篇关于Javascript/将CSS样式字符串转换为JS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!