2012-10-22 38 views
3

这里是小提琴:http://jsfiddle.net/hrQG6/Z-index嵌套绝对元素重叠相似的绝对元素?

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元件的顶部。从概念上讲,我误解了positionz-index的使用。

回答

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

.info-window元件是内部.hotspot元件,两者都具有相等z-index。想象一下:

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

因为我们有相同z-index值设定的两个<div> S,那么他们有相等的水平。第二,默认情况下,由于标记中的顺序而重叠第一个。

现在,考虑一下:

<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'); 
}); 
+0

[1]:除非你是F * CKIN'绿巨人,这有点让这个比喻没有实际意义。 –

+0

+1我非常感谢解释。我已经尝试了这一点,并更好地理解了嵌套元素的z-index属性。 – Josh

+0

有了接受的答案,它就像没有为'.hotspot'指定z-index一样简单。这是否有缺点?我首先指定了一个,这样它肯定在'#map'的*顶部*上。 – Josh

1

因为你的信息框是你的热点DIV的孩子,你会不得不影响容器的zIndex的翼:在这里打球是

$('.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/

1

的核心问题CSS堆叠的上下文,比第一眼看起来更难处理。

#hs2出现在#hs1.info-window即使其z索引值比的.info-window较低,因为.info-window#hs1后代,其中设立了一个新的堆叠内容的上方。

这里有几个很好的联系,如果你想在这个MDN读了,very good blog article by Tim Kadlec