Pregunta

How can I find which element has a z-index when you click on the link? For instance,

html,

<ul class="selected">
    <li><a href="#">1</a></li>
    <li><a href="#">2</a></li>
</ul>

<ul>
    <li class="selected"><a href="#">3</a></li>
    <li><a href="#">4</a></li>
</ul>

<ul>
    <li><a href="#" class="selected">5</a></li>
    <li><a href="#">6</a></li>
</ul>

css,

.selected {
    z-index:10;
}

If I click the link 1, then the ul has the z-index. If I click the link 3 then return li has it. If I click the link 5 then return a has it.

Is it possible?

I suppose I will use get(0).nodeName to return what node name it is. But the z-index is not on the link itself but on li or ul.

jquery,

$("a").click(function(){

    var zindex = parseInt($(this).css("zIndex"), 10);

    if(zindex) alert($(this).get(0).nodeName);

});
¿Fue útil?

Solución

For starters you would have to add a position to those elements, otherwise they won't have a z-index, and would just return auto.

.selected {
    z-index : 10;
    position: relative;
}

Then you look at the element itself, and then it's parents, to see if any of them has a matching z-index, like so:

$("a").on('click', function(e){
    e.preventDefault();
    var Zidx    = 10,
        closest = null;

    $(this).parents().addBack().each(function() {
        if ( parseInt( $(this).css('z-index'), 10) === Zidx) {
            closest = this;
            return false;
        }
    });

    if (closest) alert( $(closest).prop('tagName') );
});

FIDDLE

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top