如何在jQuery中获取所有动态设置的内联样式CSS?

3

我希望能够获取元素上动态设置的所有样式(即应用为内联样式)。

例如:

<span class="text" style="color: rgb(128, 128, 255); font-size: 24px;">Name</span>

我想将style属性的值保存在JS变量中,并获取它。我尝试使用jQuery的.attr('style'),但它返回undefined。
同时,根据这里的建议(How to get inline CSS style property from element),可以使用...
getComputedStyle

但是为了获得样式,我需要提及所有的样式,例如:

var el = document.querySelector("selector")
console.log(el.style.SomeStyle);

但是用户可以动态设置各种样式,那么我需要逐个提及所有的内联样式吗?还是有更好的方法可以实现呢?
非常感谢您的帮助。
更新自void的评论:
正如在这里描述的那样,marknadal编写了一个函数来检索内联和外部样式,但我只需要与所有附加CSS类无关的内联样式。

可能是 https://dev59.com/93RA5IYBdhLWcg3w_DHF 的重复问题。 - void
2个回答

2
您可以使用getAttribute
const el = document.querySelector('my-element');
const styleStr = el.getAttribute('style');

例如,以下内容:
<div style="color:blue;display:flex;"></div>

将会产生:

'color:blue;display:flex;'

您可以使用正则表达式或其他工具对其进行必要的解析。我建议将其转换为数组嵌套数组或类似结构,而不是对象,因为您可能会不确定哪些值可用(这是一种简单的方法,更高效的分解方法可能需要您自己完成):

// gives [ ['color', 'blue'], ['display', 'flex'] ]
str.slice(0, str.length - 1).split(';').map(x => x.split(':'))

你可以将其转换为对象并使用 for in 循环,同时还要使用 obj.hasOwnProperty(key)

jQuery 替代方案:

const els = $('my-element');
els.each((i, el) => {
  const styleStr = els.attr('style');
  const styles = styleStr.slice(0, styleStr.length - 1).split(';').map(x => x.split(':'));
});

treyhakanson,请查看我在FRS答案中发布的评论。谢谢。 - Aman Singh
1
你可以使用querySelectorAll并迭代它,它会起作用。 在jQuery中,解决方案是相同的,只需使用.attr而不是getAttribute。 我知道你说你尝试过这个并且它没有工作,但你必须在其他地方有一个错误,因为我以前使用过.attr('style'),它很好用。 - treyhakanson
1
我确实犯了一些错误,现在它已经可以工作了。非常感谢。 - Aman Singh

0
您可以按照以下方式迭代元素“style”字段下可用的对象:

警告 该对象还包含元素的所有可能样式(具有非数字属性键),因此使用例如 for (sth in styles) 的循环不会起作用。您需要以类似数组的方式迭代样式,如下所示。

var el = document.querySelector("selector");
var styles = el.style;

for (var i = 0, len = styles.length; i < len; ++i) {
    var name = styles[i];
    var value = styles[value];

    console.log(name); // shows style name, e.g.: color, padding, etc
    console.log(value); // shows style value, e.g.: #fff, 20px, etc
}

FRS 这在 jQuery 中可行吗?因为我有多个连续元素需要迭代获取,所以这个解决方案对我不起作用。 - Aman Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接