Convert HTML Element's "Style" Attribute to JSON
I need to convert the style attribute of an HTML开发者_如何学Go element to a JSON object with JavaScript / jQuery. How should I go about this?
Clarification:
Lets say I have <div style="font-size: 14px; text-align: center;"></div>
, so I want a JSON object: {font-size: 14px, text-align: center}
How about this:
function getStyles(el) {
var output = {};
if (!el || !el.style || !el.style.cssText) {
return output;
}
var camelize = function camelize(str) {
return str.replace (/(?:^|[-])(\w)/g, function (a, c) {
c = a.substr(0, 1) === '-' ? c.toUpperCase () : c;
return c ? c : '';
});
}
var style = el.style.cssText.split(';');
for (var i = 0; i < style.length; ++i) {
var rule = style[i].trim();
if (rule) {
var ruleParts = rule.split(':');
var key = camelize(ruleParts[0].trim());
output[key] = ruleParts[1].trim();
}
}
return output;
}
var element = document.querySelector('div');
var css = getStyles(element);
console.log('css ->', css);
output:
{
color: "green",
border: "1px solid orange",
marginLeft: "15px",
padding: "20px",
backgroundColor: "white"
}
fiddle:
https://jsfiddle.net/grt6gkpe/1/
Using the jquery-json plugin,
HTML
<element id="myElt" style="foo: 1; bar: x; baz: none;"/>
JavaScript
var styles = $('#myElt').attr('style').split(';'),
i= styles.length,
json = {style: {}},
style, k, v;
while (i--)
{
style = styles[i].split(':');
k = $.trim(style[0]);
v = $.trim(style[1]);
if (k.length > 0 && v.length > 0)
{
json.style[k] = v;
}
}
alert($.toJSON(json));
http://jsfiddle.net/mattball/aT77q/
You can also roll your own -- it's not that hard. The MDC documentation for style
gives ample data:
function getStyles(element) {
var style = element.style;
var ret = {};
for (var i = 0; i < style.length; ++i) {
var item = style.item(i);
ret[item] = style[item];
}
return ret;
}
Perhaps ever so slightly an off answer, but I ran into this thread looking for a way to turn the style attribute into an object, ready to pass to $(el).css(). I wound up writing this little plugin to do it:
$.fn.styleAttributeToObject = function () {
var style = $(this).attr('style'),
asObject = {};
if ('string' === typeof style) {
$.each(style.split(';'), function (i, e) {
var pair = e.split(':');
if (2 === pair.length) {
asObject[pair[0]] = pair[1];
}
});
}
return asObject;
};
Hope it's helpful to others.
You can get a string from element.style.cssText and split it up
function styleObject(element){
var obj= {},
str= element.style.cssText.match(/([^:]+\: *[^;]+); */g),
tem, i= 0, ax, L= str.length;
while(i<L){
tem= str[i++].split(/: */);
obj[tem[0]]= tem[1];
}
return obj;
}
//example- styleObject(elementreference);
/* value: (Object)
{
display: 'block;',
margin-left: '1ex;',
margin-right: 'auto;',
position: 'relative;',
width: '1193px;',
z-index: '100;',
visibility: 'visible;'
}
But why not just use the cssText string as the value?
精彩评论