获取应用于特定元素的所有css样式的列表 [英] Get the list of all css styles applied to a specific element
问题描述
是否有任何方法可以获取仅适用于特定html元素的用户定义的css样式列表.可以通过外部css文件或嵌入式/内联样式以现在可用的任何方式应用样式.
Is there any way to get the list of only user-defined computed css styles applied to a specific html element. Styles can be applied in any fashion available now either by external css file or embedded/inline style.
.p1{font-size:14px; line-height:20px;}
<style>
.p1{ line-height:18px; color:green;}
</style>
<p class="p1" style="color:red;">Some Paragraph</p>
现在我需要拥有的列表是应用于元素的唯一用户定义的计算样式,而不是 window.getComputedStyle()
Now the list I require to have, is the only user-defined computed style applied to an element not the whole bunch of computed styles containing blanks/null/default-values as provided by window.getComputedStyle()
为了更精确地回答我的问题,我想提出一个场景,我是第一次访问网站,我想使用开发人员工具栏以编程方式(或通过编写一些脚本)获得唯一的用户定义样式在控制台上).因此,考虑到这种情况,我需要的最终输出应该是-
just to be more precise on my question, I'd like to put a scenario where I visit a site first-time and I want to use developer toolbar to get the only user-defined styles programmatically (or by writing some scripts on console). So taking this scenario in mind, the final output i require should be-
{
'color':'red',
'line-height' : '18px',
'font-size' : '14px'
}
如有需要,请纠正我的查询或任何解释错误.
Please correct me on my query or any mistake in explaination, if needed.
推荐答案
您正在寻找的方法是:
window.getComputedStyle()
请参见: Mozilla开发人员网络(MDN)on Window.getComputedStyle();
http://developer.mozilla.org/zh- US/docs/Web/API/Window/getComputedStyle
Window.getComputedStyle()
方法在应用活动样式表并解决了这些值可能包含的所有基本计算之后,给出了元素的所有CSS属性的值.
The
Window.getComputedStyle()
method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
根据您问题中的标记和样式:
Based on the markup and styles in your question:
var para1 = document.getElementsByClassName('p1')[0];
var para1Styles = window.getComputedStyle(para1);
para1Color = para1Styles.getPropertyValue('color'); // red
para1FontSize = para1Styles.getPropertyValue('font-size'); // 14px
para1LineHeight = para1Styles.getPropertyValue('line-height'); // 20px
通过声明第二个(可选)参数,相同的方法还允许您从伪元素中提取样式属性值.
The same method will also allow you to pull style property values from pseudo-elements, by declaring the second (optional) argument.
例如
var para1AfterStyles = window.getComputedStyle(para1, ':after');
这篇关于获取应用于特定元素的所有css样式的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!