这是小提琴: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 上。从概念上讲,我误解了position
和z-index
的使用。
答案 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)
答案 2 :(得分:1)
您应该为父元素定义z-index
属性,目前它们都具有相同的z-index值。
#hs1 {
top: 10px;
left: 20px;
z-index: 2;
}
#hs2 {
top: 150px;
left: 120px;
z-index: 1;
}
答案 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
});
答案 4 :(得分:1)
这里发挥的核心问题是CSS堆叠上下文,这比看起来乍一看更难以理解。
#hs2
显示在.info-window
#hs1
上方,即使其z-index值低于.info-window
,因为.info-window
是#hs1
的后代{{1}},它建立了一个新的堆叠环境。