开发者

Finding z-index value using jQuery

开发者 https://www.devze.com 2023-01-07 15:02 出处:网络
How to find a z-index value of a element by jQuery? i.e.: I have 2 divs, both are positioned absolute and z-index 10, 1000 respectively.

How to find a z-index value of a element by jQuery?

i.e.: I have 2 divs, both are positioned absolute and z-index 10, 1000 respectively.

But unfortunately IE6 displaying second div which has z-index 1000 below the first one.

So I want to check what the z-index value of second one and first one at run time in IE6.开发者_C百科

Please help.


You can get it using css.

$("#your-div").css("z-index");

Ref: http://api.jquery.com/css/


You can use $('selector').zIndex().

DO NOT USE $('selector').css('z-index'). It will only tell you what (if anything) was set in the style sheet. It may just say "auto".


If they have IDs for example (or any selector you can find them by) use .css(), like this:

var zIndex = $("#div1").css('z-index');

Or the more complete:

alert("Div 1 zIndex: " + $("#div1").css('z-index'));
alert("Div 2 zIndex: " + $("#div2").css('z-index'));


Like the css() function ?

alert($('#my_object_id').css('zIndex'));


jQuery provides methods to directly set and get z-index of any element

Syntax:

var index = $("#div1").zIndex()


$(elem).css('z-index');

Also, where are you setting the z-indexes. If it's in an inline style vs a style block, then you may see different results. So:

<div style="z-index: 1000">..</div>

vs

<style>
div {
    z-index: 1000;
}
</style>

may give different results. Also, remember that going by your logic is an exercise in vain with IE.


Your code must be broken. Check this, it works.

If you don't set a z-index value FF and Chrome will display auto, and IE 0.

Undefined means there is some error in your code.


Besides using

$('selector').css('z-index')

you have to add postion:absolute or position:relative in your styles to element with z-index you want to get.


what about something like

var zindex = $("#id").css("z-index");


use zIndex instead of z-index.

$('selector').css('zIndex');


I made a simple recursive function to get the exact zIndex value in number

function getRecursiveParentZIndex(jqThis) {
  try {
    let thisTagName = jqThis.prop('tagName');

    let thisZIndex = jqThis.css('z-index');
    if (thisZIndex == '' || thisZIndex == 'auto') {
      thisZIndex = 0;
      if (thisTagName != 'HTML') {
        let newZIndex = getRecursiveParentZIndex(jqThis.parent());
        thisZIndex = newZIndex;
      }
    }

    return +thisZIndex;
  } catch (error) {
    console.log('parent Z Index error', error);

    return 0;
  }
}

let correctZindex = getRecursiveParentZIndex(jQuery('.your-selector'));

This will return the correct z-index value in number. (Note that i used ES6 syntax)

0

精彩评论

暂无评论...
验证码 换一张
取 消