【问题标题】:Displaying element behind other with z-index doesn't work [duplicate]使用 z-index 在其他元素后面显示元素不起作用[重复]
【发布时间】:2013-04-17 12:29:24
【问题描述】:

我创建了这个小提琴来说明我的问题: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 元素看起来像橙色背景,但是因为我希望荧光笔在宽度和位置上设置动画,所以我不能只给这些元素本身设置背景。

【问题讨论】:

  • + "px" 不是明确需要的,因为您也没有将它用于顶部和左侧。我认为 z-index 也是多余的,因为荧光笔元素是容器内的第一个元素,请参见小提琴:jsfiddle.net/AVxbd/7(我将荧光笔移到了末尾,所以它是最后一个元素)
  • @Imperative 是的,我只是添加它们以确保 不是问题。感谢您指出!

标签: javascript jquery html css z-index


【解决方案1】:

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

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

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

【讨论】:

【解决方案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.

【讨论】:

  • 位置总是被定义,但默认是'静态'
  • 只是想让您知道关于链接到 w3schools 的 helpful question
  • 我的立场是正确的,谢谢。
【解决方案3】:

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

SEE DEMO

【讨论】:

    猜你喜欢
    • 2023-02-24
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多