2012-10-22 107 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

相關問題