Mechlar
Mechlar

Reputation: 4984

IE returns wrong z-index

So here is another z-index issue in IE7 I have ran into. I found an explanation of the problem else where but without a fix.

When you have a positioned element with an inline z-index of 0, javascript doesn't return the correct z-index. If a z-index is set to the element in a stylesheet it will return that z-index instead. I get the same result using jQuery too.

Make an html file with the following:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
   $(function(){
      $('button').click(function(){
         alert($('#mainBox').css('zIndex'));
      });
   });
</script>
<style type="text/css">
   #mainWr {
      position: relative;
      z-index: 2;
      border: 1px solid #333;
      width: 200px;
      height: 200px;
   }
   #mainBox {
      z-index: 1;
      border: 1px solid #555;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 50px;
      left: 50px;
   }

</style>

<div id="mainWr">
   <div id="mainBox" style="z-index: 0;"></div>
</div>
<br />
<button type="button">Show #mainBox z-index</button>

Open that in IE7. The problem does not exist in IE8.

I jsfiddled it if you have IE7, otherwise you will need to use the code and display it with whatever method you use to emulate IE7:

http://jsfiddle.net/dalelarsen/DndnM/

I am not aware of any solutions. Any comments are welcome.

Upvotes: 0

Views: 239

Answers (2)

Mechlar
Mechlar

Reputation: 4984

Okay, I solved this. The solution is to make sure you grab exactly what is inline yourself and don't rely on the browser.

So I wrote a small object (as a jquery plugin) that parses what is in the element's style attribute and returns the correct value. I am using this for getting the z-index but I wrote it to return any style. You have to pass in the style being requested using the real css name of the style, e.g. 'z-index' instead of 'zIndex'. Maybe at some later day I will rewrite it to account for camel case.

Anyway, here it is:

jQuery.fn.inlineStyle = function(stylesName){

   var allStyles = this.attr('style');

   var allStylesArr = allStyles.split(';');
   var allStylesObj = {};
   for (var i = 0; i < allStylesArr.length; i++) {
      var parts = allStylesArr[i].split(':');
      allStylesObj[$.trim(parts[0]).toLowerCase()] = $.trim(parts[1]);
   }
   var rStyleVal = false;
   if (allStylesObj[stylesName]) rStyleVal = allStylesObj[stylesName];
   return rStyleVal;
};

Upvotes: 0

Woot4Moo
Woot4Moo

Reputation: 24336

If I am not mistaken providing a negative z-index resolves this issue. A developer here ran into that issue and I believe that was the resolution.

Upvotes: 1

Related Questions