简体   繁体   English

如何返回外部样式表类应用于元素的所有CSS属性(而不是计算样式!)?

[英]How do I return all CSS properties applied to an element by an external stylesheet class (not get computed styles!)?

Given css class: 给定CSS类:

.red {
    color: rgb(255,0,0);
   background-color: rgb(0, 255, 0);
}

I then add a div to the dom via: 然后,我通过以下方式将div添加到dom:

$("<div></div>").addClass("red").hide().appendTo("body");

I can get single properties using: 我可以使用以下方法获取单个属性:

$(".red").css("color");

Which returns rgb(255, 0, 0); 返回rgb(255,0,0);

My question is how can I loop through the css class properties and return them all without directly using the property name? 我的问题是如何在css类属性中循环并返回它们,而无需直接使用属性名?

I've actually found a solution using this very handy jQuery library: https://github.com/f0r4y312/jquery-stylesheet 我实际上已经找到了使用此非常方便的jQuery库的解决方案: https : //github.com/f0r4y312/jquery-stylesheet

I can now loop through each stylesheet and the declaration and return: 我现在可以遍历每个样式表和声明并返回:

var key is a loop through the css property names
$.stylesheet("." + key + "").rules()[0].style

Which then returns all the style properties: 然后返回所有样式属性:

0 "color" "rgb(255, 0, 0)"
1 "background-color" "rgb(0, 255, 0)"
etc

Which I'm now serialising into a json array for a unit test! 我现在将其序列化为一个json数组以进行单元测试!

Thanks for all your very helpful replies! 感谢您的所有非常有帮助的回复!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 css样式何时/如何应用于动态添加的元素? - when/how do css styles get applied for dynamically added element? 如何在 Javascript 中获取元素及其子元素的所有计算 css 属性 - How get all computed css properties of element and its children in Javascript 是否可以获得所有应用的样式而不仅仅是计算出的样式 - Is it possible to get all applied Styles and not just the computed 获取元素的所有DEFINED(在stylesheet / inline中)css样式 - Get ALL DEFINED( in stylesheet/inline ) css styles of an element 获取应用于特定元素的所有CSS样式的列表 - Get the list of all css styles applied to a specific element 如何获取所有计算属性的列表? - How do I get a list of all computed properties? 如何确定所有直接应用于元素的 CSS styles? - How to determine all CSS styles that are applied directly to an element? 如何仅通过提供元素的 id 来获取元素的所有应用样式? - How to get all the applied styles of an element by just giving its id? jQuery - 如何使用元素的HTML获取所有样式/ css(在内部/外部文档中定义) - jQuery - How to get all styles/css (defined within internal/external document) with HTML of an element 如何将所有计算的样式设置为元素上的文字样式? - How to set all computed styles as literal styles on an element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM