如何通过只给它的id来获取元素的所有应用样式? [英] How to get all the applied styles of an element by just giving its id?
问题描述
我试图写一个函数,它接受元素的Id,并给出所有样式属性(及其值)的列表应用于该元素。它应该考虑内联样式以及在css文件中定义的样式。
I was trying to write a function which takes the Id of an element and gives the list of all the style attributes(with their values) applied on that element. It should consider the inline style as well as the style defined in css file.
我可以得到函数工作,当我提供样式属性名称与元素的id in参数,但我只是想传递的元素的id,应该能够获得所有的样式属性以及值。
I could get the function work when I provide style attribute name along with the id of the element in parameter but I just want to pass the id of the element and should be able to get all the style attributes along with values.
函数应该是像getStyleById );
function should be something like getStyleById(elementId);
PFB目前为止的代码片段:
PFB the code snippet so far:
var styleNode = [];
var styles;
var sty = x.style;
var len = sty.length;
for (var i = 0; i < len; i++) {
styles = sty.item(i);
if (x.currentStyle) //IE for External/Global Styles
{
var a = x.currentStyle[styles];
styleNode.push(styles + ":" + a);
}
else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox,Chrome,Safari for External/Global Styles
{
var b = document.defaultView.getComputedStyle(x, "").getPropertyValue(styles);
styleNode.push(styles + ":" + b);
}
else //Works in Inline Styles only
{
var c = x.style[styles];
styleNode.push(styles + ":" + c);
}
}
任何帮助将不胜感激。
尊敬的,
manishekhawat
manishekhawat
推荐答案
使用以下方法:
- 遍历
CSSStyleDeclaration
对象( getComputedStyle )以获取每个已知的属性名称。使用getPropertyValue
+这个名称来获取值。
代码优化:不要使用getComputedStyle
- 使用普通的
for(name in object)
循环currentStyle
。 - 对内联样式使用相同的循环方法
- Loop through the indexes of the
CSSStyleDeclaration
object (getComputedStyle) to get each known property name. UsegetPropertyValue
+ this name to get the value.
Code optimalization: Do not usegetComputedStyle
for each iteration, but store it in a variable outside the loop. - Use an ordinary
for ( name in object )
loop forcurrentStyle
. - Use the same looping method for inline styles
代码:
function getStyleById(id) {
return getAllStyles(document.getElementById(id));
}
function getAllStyles(elem) {
if (!elem) return []; // Element does not exist, empty list.
var win = document.defaultView || window, style, styleNode = [];
if (win.getComputedStyle) { /* Modern browsers */
style = win.getComputedStyle(elem, '');
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style.getPropertyValue(style[i]) );
// ^name ^ ^ value ^
}
} else if (elem.currentStyle) { /* IE */
style = elem.currentStyle;
for (var name in style) {
styleNode.push( name + ':' + style[name] );
}
} else { /* Ancient browser..*/
style = elem.style;
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style[style[i]] );
}
}
return styleNode;
}
这篇关于如何通过只给它的id来获取元素的所有应用样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!