【问题标题】:CSS Positioning div on top with z-indexCSS 定位 div 顶部与 z-index
【发布时间】:2014-01-14 14:28:25
【问题描述】:

我有一个包含三个 div 的容器。每个 div 包含一个隐藏的 div,其中有一个“隐藏”类 (display:none;),当悬停在其父 div 上时应该显示该类。

我使用toggleClass('show') 使secretDiv 显示有一个块。将鼠标悬停在父 div 上时,我需要显示 secretDiv。

父 div 应该显示在下面的 div 之上,而不是推送其他 div

http://jsfiddle.net/2xLMQ/4/

--- HTML ---

<div class="row">
    <div class="element">
        <img src="http://placehold.it/200x100" alt="" title="" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
    <div class="element">
        <img src="http://placehold.it/200x100" alt="my image" title="image title" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
</div>

<div class="row">
    <div class="element">
        <img src="http://placehold.it/200x100" alt="" title="" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
    <div class="element">
        <img src="http://placehold.it/200x100" alt="my image" title="image title" />
        <div class="secretDiv hide">
            <p>Some secret text and stuff</p>
        </div>
    </div>
</div>

--- CSS ---

.hide {display:none;}
.show {display:block;}
.row {height:160px;background:#dedede;float:left;width:480px;position:relative:z-index:1;}
.row .element {position:relative;z-index:9;text-align:center; float:left; background:#666;width:200px;padding:12px;margin:6px;}
.row .image {}
.row .secretDiv {background:#ff0000;padding:8px;}

--- JS ---

$('.element').hover(function(){
    $('.element .secretDiv').toggleClass('show');
});

【问题讨论】:

标签: html css css-position z-index


【解决方案1】:

首先将您的选择器更改为仅匹配相应的隐藏 div:

 $('.secretDiv',this).toggleClass('show');

然后在该项目上添加另一个类以显示在其他类之上:

$(this).toggleClass('ontop');

还有班级:

.row .ontop {z-index:10;background:orange;}

查看Demo

【讨论】:

  • 不知道为什么你被否决了,但是为什么额外的 .ontop 类?
  • @j08691 只是为了允许在 div 中进行更多更改,如果他想像背景一样突出显示。但他当然可以只更改z-index
  • @Danko - 亲爱的,您的解决方案运行良好。正是我需要的。不知道我可以在(这个)选择器之后指定一个类。从您的解决方案中学习,非常感谢。选择的答案 + 赞成。
【解决方案2】:

只需将绝对定位添加到您的“秘密”div:

.row .secretDiv {background:#ff0000;padding:8px; position: absolute; top: 5px; left: 5px;}

在这里提琴:http://jsfiddle.net/moonspace/2xLMQ/12/

作为奖励,我已经编辑了您的 jQuery 以仅显示与每个元素关联的“秘密”div:

$('.secretDiv', this).toggleClass('show');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-22
    • 2012-07-05
    • 2011-05-08
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多