使用z索引将元素显示在其他元素后面;不起作用

Displaying element behind other with z-index doesn't work

本文关键字:元素 不起作用 其他 显示 索引 使用      更新时间:2023-09-26

我创建了这个fiddle来说明我的问题:http://jsfiddle.net/AVxbd/

我有一个菜单(#container(,有一些链接(#text1#text2(。我制作了一个#highlighter元素来突出显示此人在特定时刻所在页面的链接。HTML:

<div id="container">
    <div id="highlighter"></div>
    <div id="text1">Text 1</div><div id="text2">Text 2</div>
</div>

JavaScript:

$('#highlighter')
    .offset($('#text1').offset())
    .width($('#text1').width()
);
$('#text1, #text2').click(function(){
    $('#highlighter').animate({
        top: $(this).offset().top,
        left: $(this).offset().left,
        width: $(this).width() + "px"
    },300);
});

问题是#highlighter元素显示在#text1#text2元素之上。那不是我想要的!

我试图用z索引来解决这个问题:

#container {     z-index: 1; }
#highlighter {   z-index: 2; }
#text1, #text2 { z-index: 3; }

然而,正如你在小提琴上看到的那样,这是行不通的。

我怎样才能让它发挥作用?我想让它看起来像#text1#text2元素有一个橙色的背景,但因为我想让荧光笔在宽度和位置上设置动画,所以我不能只给这些元素本身一个背景。

position: relative;添加到#text1, #text2

http://jsfiddle.net/AVxbd/2/

z索引仅适用于已定位的元素。

#text1, #text2 {
cursor: pointer;
display: inline-block;
font-size: 30px;
height: 50px;
line-height: 50px;
text-align: center;
z-index: 3;
*position:relative;*

}

位置添加到此类。如果未定义位置,则Z索引不起作用。

有关位置和z索引的详细信息,请单击此处。

只需为#text1和#text2 设置position:relative;

参见演示