如何表征DOM的Z-indexing? (2) [英] How to characterize z-indexing for the DOM? (2)
问题描述
我想要遍历DOM并报告所有的z-索引与其各自的ID。
例如:
id z -index
header 10
main 0
菜单20
最终结果将是一个对象,其键是元素id,该值是z-index。有人可能称之为 z_obj
//伪代码
var z_obj = {el_id:el_zindex};
获取每个元素的z-index( el
)应该很容易使用像 filter
和下面的代码:
// attr是属性
data = _.filter(el.attributes,function(attr){
return(/^z-index/).test(atttr.name);
});
但是,如何遍历DOM以获取所有z索引并将其存储在对象中? / p>
我想这样做不出库,如果可能,使用上面的代码。
将会是一个很好的调试工具。
您可以使用 getElementsByTagName(*)
,在集合中,使用 window.getComputedStyle(Node)
。从那里,您可以检索 z-index
。这里有一个例子:
var zObj,allEls,i,j,cur,style,zIndex;
zObj = {};
allEls = document.body.getElementsByTagName(*);
for(i = 0,j = allEls.length; i< j; i ++){
cur = allEls [i];
style = getComputedStyle(cur);
zIndex = style.getPropertyValue(z-index);
zObj [cur.id] = zIndex;
}
演示: http://jsfiddle.net/mj3cR/1/
其中 zObj
是一个对象,由 id
属性表示的键,以及 z-索引
样式。
请注意,IE< code> getComputedStyle 9,但当然有许多polyfills :)
I've been a bit care-less with choosing z-indexes in my CSS.
I'd like to traverse the DOM and report all the z-indexes with their respective ID's.
For example:
id z-index
header 10
main 0
menu 20
The end result would be an object whose keys are the element id and the value is the z-index. One might call it z_obj
// pseudo code
var z_obj = {el_id: el_zindex};
Getting the z-index for each element ( el
) should be easy using something like filter
and the code below:
// attr is attribute
data = _.filter(el.attributes, function (attr) {
return (/^z-index/).test(atttr.name);
});
But how would I traverse the DOM to get all z-indexes and store that in an object?
I'd like to do this w/ out libraries, and using the code above if possible.
This would be a good debug tool in general.
You can get all elements with getElementsByTagName("*")
, iterate over the collection with a for
loop, and use window.getComputedStyle(Node)
. From there, you can retrieve the z-index
. Here's an example:
var zObj, allEls, i, j, cur, style, zIndex;
zObj = {};
allEls = document.body.getElementsByTagName("*");
for (i = 0, j = allEls.length; i < j; i++) {
cur = allEls[i];
style = getComputedStyle(cur);
zIndex = style.getPropertyValue("z-index");
zObj[cur.id] = zIndex;
}
DEMO: http://jsfiddle.net/mj3cR/1/
Where zObj
is an Object, keys represented by the id
attributes, and values represented by the z-index
style.
Note that getComputedStyle
is not supported in IE < 9, but of course there are many polyfills :)
这篇关于如何表征DOM的Z-indexing? (2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!