是否可以使用javascript或jquery遍历div的样式属性? [英] Is it possible to loop through the style attributes of a div with javascript or jquery?
问题描述
正如标题所说,我想知道是否可以使用javascript或jquery遍历div的样式属性。我想要做的是遍历样式并创建一个包含这些样式名称和值的对象。
As the title says I am wondering if it is possible to loop through the style attributes of a div with javascript or jquery. What I want to do is loop through the styles and create an object containing these style names and values.
这是我要做的一个例子:
Here is an example of what I am trying to do:
alert($('#mydiv').attr('style'));
给出以下内容:
background-color: #CCCCCC; border-width: 2px; border-style: solid; width: 250px;
我想创建一个如下所示的对象:
And I want to create a object which looks like this:
{"background-color":"#CCCCCC","border-width":"2px","border-style":"solid","width":"250px"}
我无法弄清楚这是否可以通过循环执行来实现样式或是否必须使用类似下面的代码自己创建对象:
What I can't figure out is whether this is achievable by looping through the styles or whether I will have to create the object myself using code similar to below:
var style = {};
style['width'] = $('#mydiv').css('width');
任何意见的输入都将受到赞赏。
Any input of this would be appreciated.
推荐答案
这样做你想要的吗?
var parts = style.split(";")
var obj = {}
for (var i=0;i<parts.length;i++) {
var subParts = parts[i].split(':');
obj[subParts[0]]=subParts[1];
}
这篇关于是否可以使用javascript或jquery遍历div的样式属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!