嵌套绝对元素的Z-index重叠相似的绝对元素?

时间:2012-10-22 22:07:52

标签: jquery css

这是小提琴:http://jsfiddle.net/hrQG6/

HTML

<div id='map'>
    <div class='hotspot' id='hs1'>
        <div class='info-window'>
            Foobar
        </div>
    </div>
    <div class='hotspot' id='hs2'>
        <div class='info-window'>
            Foobar
        </div>
    </div>
</div>

CSS

.hotspot {
    position: absolute;
    z-index: 10;
    background-color: blue;
    height: 30px;
    width: 30px;
} 
.info-window {
    display: none;
    height: 250px;
     width: 250px;   
    background-color: green;
    position: absolute;
    z-index: 9999;
}​

.hotspot元素显示在容器中。默认情况下,.info-window元素不会显示。点击.hotspot将显示其对应的.info-window。不过,我希望.info-window涵盖其下的所有.hotspot元素。

相反,.hotspot元素位于.info-window元素的 top 上。从概念上讲,我误解了positionz-index的使用。

5 个答案:

答案 0 :(得分:3)

您的.info-window个元素位于.hotspot元素内,两者都相等z-index。想象一下:

<div></div>
<div></div>

由于我们将两个<div>设置为具有相等的z-index值,因此它们具有相同的级别。默认情况下,第二个因为标记中的顺序而与第一个重叠。

现在,请考虑一下:

<div><div class="inner"></div></div>
<div><div class="inner"></div></div>

无论你给第一个z-index元素.inner,它总是位于第二个<div>容器下面,只是因为第一个.inner元素是<div>容器已位于第二个下面。

这就像试图从建筑物的一楼尽可能高地跳跃:无论你跳得多高,你都永远不会高于二楼,因为你最终会撞上天花板,这会阻止你从更高的位置开始。[1]

更好的方法是使用或多或少相同的标记:

<div class="hotspot">
    <div class="info"></div>
</div>

并在.hotspot上使用或多或少相同的CSS规则:

.hotspot {
    position:absolute;
    z-index:10;
}

.hotspot .info {
    display:none;
}

然后,引入一个覆盖它的标志类:

.hotspot.active {
    z-index:20; /* let's raise this a bit */
}

.hotspot.active .info {
    display:block;
}

然后使用Javascript操作:

var hotspots = $('.hotspot').on('click', function (e) {
    hotspots.removeClass('active');
    $(this).addClass('active');
});

答案 1 :(得分:2)

删除

z-index: 10;

来自你的.hotspot我相信它可以解决你的问题。

updated fiddle

答案 2 :(得分:1)

您应该为父元素定义z-index属性,目前它们都具有相同的z-index值。

#hs1 { 
    top: 10px;
    left: 20px;
    z-index: 2;
}    
#hs2 { 
    top: 150px;
    left: 120px;
    z-index: 1;
}  

http://jsfiddle.net/MMj8S/

答案 3 :(得分:1)

因为你的信息框是你的热点div的孩子,你必须影响容器的zIndex ala:

$('.hotspot').click(function() {
    $('.hotspot').css('zIndex', 1);  //Force all hotspots to the back
    $(this).css('zIndex', 9999);  //force this hotspot to the front
    $('.info-window').hide();  //Hide all infoboxes, in case of overlap
    $(this).find('.info-window').show();     //show the infobox inside this div
});​

http://jsfiddle.net/hrQG6/3/

答案 4 :(得分:1)

这里发挥的核心问题是CSS堆叠上下文,这比看起来乍一看更难以理解。

#hs2显示在.info-window #hs1上方,即使其z-index值低于.info-window,因为.info-window#hs1的后代{{1}},它建立了一个新的堆叠环境。

如果您想阅读MDNvery good blog article by Tim Kadlec

,请参阅以下几个好的链接