使用z-index显示其他元素后面的元素不起作用

时间:2013-04-17 12:29:25

标签: javascript jquery html css z-index

我创造了这个小提琴来说明我的问题: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-index解决这个问题:

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

然而,这不起作用,正如你可以在小提琴中看到的那样。

我怎样才能让它发挥作用?我想让它看起来像#text1#text2元素具有橙色背景,但是因为我希望荧光笔在宽度和位置上设置动画,所以我不能仅仅为这些元素赋予背景。

3 个答案:

答案 0 :(得分:8)

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

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

z-index仅适用于定位元素。

答案 1 :(得分:2)

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

}

位置添加到此课程。如果未定义位置,则Z-index不起作用。

For details on position and z-index, click here.

答案 2 :(得分:0)

只需为#text1和#text2

设置position:relative;

SEE DEMO

相关问题