【问题标题】:CSS. Parent > Child1:hover. How to display Parent > Child2?CSS。父>子1:悬停。如何显示父>子2?
【发布时间】:2011-12-06 02:55:37
【问题描述】:

希望我的问题的标题足够清楚。

这是我的 CSS 组合框的一个非常简单的版本。我想我只是错过了一些小事,希望你能帮忙。基本上我有一个容器 Div,然后我有一个下拉 Div,其中包含右侧的浮动按钮。在这个下拉 Div 中,我还有一个 Menu Div,它在用户悬停浮动按钮 Div 之前一直隐藏。

我可以通过将鼠标悬停在下拉 Div 上来使其工作,因为菜单 Div 是它的子级但是​​,我希望能够将鼠标悬停在按钮 Div 上,该按钮是下拉 Div 的第一个子级并显示菜单 Div,这是下拉 div 的第二个子元素,而不是按钮 div 的第二个子元素。

有没有办法做到这一点?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">


#container {
position: relative;
background-color: #999999;
height: 31px;
width: 200px;
}

#container #dropdown {
background-color: #999999;
height: 31px;
width: 200px;
}

#container #dropdown #button {
float: right;
background: #555555 url('assets/img/ddw.png') no-repeat center;
height: 25px;
width: 25px;
margin-top: 3px;
margin-right: 3px;
}

#container #dropdown #button:hover #menu  {
display: block;
float: right;
background: #555555 url('assets/img/ddw.png') no-repeat center;
height: 25px;
width: 25px;
margin-top: 3px;
margin-right: 3px;

}

#container #dropdown #menu {
display: none;
position: absolute;
background-color: #777777;
top: 32px;
height: 200px;
width: 200px;
}


</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>index</title>
</head>
<body>

<div id="container">

<div id="dropdown">

<div id="button"></div>
<div id="menu">
Option 1
<br/>
Option 2
<br/>
Option 3
</div>
</div>



</div>


</body>
</html>

【问题讨论】:

    标签: css


    【解决方案1】:

    由于#menu#button 之后,您可以使用相邻兄弟选择器(+)代替后代选择器(空格):

    #container #dropdown #button:hover + #menu  {
    display: block;
    float: right;
    background: #555555 url('assets/img/ddw.png') no-repeat center;
    height: 25px;
    width: 25px;
    margin-top: 3px;
    margin-right: 3px;
    
    }
    

    【讨论】:

    • 我只是勉强把这些放在一起。如果您有更好的实践“DIV 放置建议,请随时提出建议。现在就尝试您的东西。等一下。顺便说一句,使用 (+) 是否使它成为 CSS3?
    • 哇。多么令人难以置信的简单解决方案。非常感谢伙计。顺便说一句,如果我将“悬停”切换为“活动”,有没有办法让它在用户单击它时保持可见,直到他再次单击它或单击页面上的任何其他位置?
    • @Vini:你需要一点 JavaScript,因为 :active 不是这样工作的。
    • 请注意:相邻兄弟选择器在 IE6 中不起作用。如果您正在争取 IE6 兼容性,请参阅下面的解决方案。
    【解决方案2】:

    尝试将您的div#menu 放入您的div#button。然后,为div#menu 赋予以下属性:position: relativedisplay: blocktop: 25px。给你的button div 一个overflow: hidden。然后,将您的#container #dropdown #button:hover #menu 选择器更改为#container #dropdown #button:hover,并为其赋予以下属性:width: autoheight: autooverflow: visible。有关工作示例,请参阅此 jsFiddle:http://jsfiddle.net/kzEek/

    【讨论】:

      猜你喜欢
      • 2017-11-21
      • 2010-12-21
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多