是否可以使用javascript或jquery遍历div的样式属性? [英] Is it possible to loop through the style attributes of a div with javascript or jquery?

查看:48
本文介绍了是否可以使用javascript或jquery遍历div的样式属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我想知道是否可以使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆