Can't set z-index via CSS
<html>
<head>
<title>Sample</title>
<script>
window.onload = function()
{
alert(document.getElementById('div1').style.zIndex);
alert(document.getElementById('div2').style.zIndex);
}
</script>
<style type="text/css" media="screen">
#div2
{
z-index: 1;
}
</style>
</head>
<body>
<div id="div1" style="z-index:1"></div>
<div id="div2"></div>
</body>
The outcome of the above code is "1" for the 1st alert, and nothing for the 2nd.
How come i can't set the z-index of "div2" via CSS?
T开发者_如何转开发hanks.
1: it is set, but JS cant determine it if it's not set inline
2: it would'nt have any effect, if the object is not positioned(as gulbrandr posted)
regarding to 1. If it's not set inline(or by javascript), you can retrieve it using currentStyle or getComputedStyle what gives you the currently applied style.
From W3Schools.com:
z-index only works on positioned elements (position:absolute, position:relative, or position:fixed)
The .style.*
set of properties map directly on to properties set via the style
attribute, not those which are cascaded from a proper stylesheet.
To find the computed z-index, you need to use getComputedStyle
精彩评论