z-index of an element without a closed position

Asked

Viewed 517 times

6

It is possible to know the z-index of an empty element using javascript?

For example in this code:

CSS

#exemplo1 {
    z-index:4;
}
#exemplo2 {
    z-index:4;
    position: relative;
}

HTML

<div id="exemplo1"></div>
<div id="exemplo2"></div>

It is possible to obtain the z-index of exemplo1, in this case 4, although the position is not closed?

What I have tested:

var e1 = document.getElementById('exemplo1');
var e2 = document.getElementById('exemplo2');
console.log(e1.style.zIndex); // nada
console.log(e2.style.zIndex); // nada
console.log(window.getComputedStyle(e1).getPropertyValue("z-index")); // auto no Chrome, 4 no IE11 e FF
console.log(window.getComputedStyle(e2).getPropertyValue("z-index")); // 4

jsFiddle

  • If the computed style is returning auto, is because the rendering engine will not consider the z-index for this element (will not change its z-index, nor create a new stacking context). In this case, what is the usefulness of getting the value as defined in the CSS?

  • @mgibsonbr, the curious thing is that the IE11 and the FF return 4 but Chrome returns auto. What I’m looking for is a uniform/consistent way to do this.

  • This is a bug that affects all Webkit. It is documented but still in unconfirmed status: https://bugs.webkit.org/show_bug.cgi?id=122416

1 answer

2


My only suggestion is to momentarily change the position of your element to relative, observe the z-index, and then back to the way it was before:

var pos = e1.style.position;
e1.style.position = "relative";
console.log(window.getComputedStyle(e1).getPropertyValue("z-index"));
e1.style.position = pos;

Example. How the Javascript execution on the main page is synchronous, This won’t cause any visual Glitch.

  • I also thought of this solution but I’m not sure that different browsers read the absence of position consistently. I’ll take a look... though: +1

  • Using only var pos = e1.style.position; not enough... http://jsfiddle.net/8XKXk/

  • @Sergio You don’t understand, I read this position only to reassign it after reading the z-index (because I want it to be the same as before), but it does not necessarily correspond to the computed position. And as for the behavior of different browsers, they have that return the z-index correct, according to the specification. If they don’t, it’s a bug. See that related question.

  • Okay, I see, to "trick" the browser. Yes indeed that model leaves no trace. Thank you!

  • 1

    By the way, if you have any ideas getComputedStyle join here. I’ll look too.

  • @Sergio Has tried one Shim? Here for example has a. I would test, but I am without any usable version of IE here...

  • I’ll take a look! Thanks

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.