问题
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.
回答1:
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 :)
回答2:
reportZ = function () {
var z_arr = {},
all_el = document.body.getElementsByTagName("*"),
i,
len,
cur,
style,
z_index;
for (i = 0, len = all_el.length; i < len; i++) {
cur = all_el[i];
style = win.getComputedStyle(cur);
z_index = style.getPropertyValue("z-index");
if (z_index !== "auto") {
z_arr[i] = [cur.id, cur.tagName, cur.className, z_index];
}
}
return z_arr;
};
来源:https://stackoverflow.com/questions/18106571/how-to-characterize-z-indexing-for-the-dom-2