How can I get a child of an element with lower z-index on front of a child of another element with higher z-index?

前端 未结 5 991
甜味超标
甜味超标 2021-01-20 01:27

I have the following setup:

Whatever
<
5条回答
  •  伪装坚强ぢ
    2021-01-20 02:19

    Nice design.

    Ok so I'll first say that I believe the solution to your layering problem, as others have already suggested, is moving that box outside of its parent (the map).

    But you set some constraints, so I'll try to break as few as possible. I don't know how to do this without breaking any of your constraints. Z-index is inherited (again, others have pointed this out), so you can't break out of your parents' layer with only that tool.

    So here's one way you could get the same effect, using javascript. It's ugly, and might cause you more headaches later, but it should at least work:

    1. Find out the absolute position of the div that you want to put on top.
    2. Make a copy of it.
    3. Hide the original (optional if it's opaque).
    4. Insert the copy on top of everything.

    If you're using jQuery, you can get elements' position relative to the document with the .offset() function. After that it's fairly simple:

    $(document).ready( function() {
    
        $("a[href='#overlay']").click( function() {
            // 1: get the position
            pos = $('.wrap').offset();
            // 2: make a copy
            halecopy = $('.bottom .wrap').clone();
            // 3: hide the original
            $('.bottom .wrap').css({opacity: 0});
            // 4: Insert new label on top of everything
            $('body').prepend(halecopy);
            // position the new label correctly
            halecopy.css({position:'absolute',
                          top: pos.top,
                          left: pos.left,
                          'z-index': 2});
            // show the "top" layer
            $('.top').fadeIn();
        });
    
        $("a[href='#hide']").click( function() {
            $('.top').fadeOut( function() {
                // remove the label copy
                halecopy.remove();
                // show the original again
                $('.bottom .wrap').css({opacity: 1});
            });
        });
    
    });​
    

    That script works for me on this markup:

    Whatever

    Haaaleluuuuia!

    show hide

    With these styles:

    .top,
    .bottom {
        position: absolute;
        top: 10%;
        left: 3%;
    }
    
    .top {
        z-index: 1;
        padding: 2%;
        background: rgba(0, 127, 127, 0.8);
        display:none;
    }
    
    .bottom {
        z-index: -1;
        padding: 3%;
        background: rgba(127, 127, 0, 0.8);
    }
    
    .label {
        color: #fff;
    }
    
    .wrap {
        outline: 1px dashed rgba(127, 0, 0, 0.8);
        background: rgba(127, 127, 127, 0.8);
    }
    
    .bottom .label {
        z-index: 10;
    }
    ​
    

    And here's a handly jsfiddle demo.

提交回复
热议问题