如何使用css隐藏列表并在鼠标位于上部时显示?

时间:2012-09-04 17:41:06

标签: html css list navigation

我有这个菜单:

home
Pictures
Picture 1
Picture 2
Sounds
Videos

我希望隐藏Picture 1Picture 2,除非我将鼠标移到"Pictures"

2 个答案:

答案 0 :(得分:1)

你必须在这里使用javascript,CSS本身没有任何逻辑。 将图片1和图片2的显示属性设置为无,然后当鼠标悬停在图片上时,用javascript设置它。 使用PrototypeJS,您可以执行类似

的操作
$("pictures").observe("mouseover", function(){ $("Picture 1").setStyle({display: "block"}) } )
$("pictures").observe("mouseout", function(){ $("Picture 1").setStyle({display: "none"}) } )

答案 1 :(得分:0)

因为您的问题中明显缺乏信息,尽管我对此问题有自己的评论,但我会猜测您的HTML并假设您使用ul元素来包含您的列表:

<ul>
    <li>home</li>
    <li>Pictures
        <ul>
            <li>Picture 1</li>
            <li>Picture 2</li>
        </ul></li>
    <li>Sounds</li>
    <li>Videos</li>
</ul>​

如果是这种情况,那么我建议使用以下CSS:

ul ul {
    display: none;
}

ul li:hover ul {
    display: block;
}​

JS Fiddle demo

鉴于我怀疑你正试图制作某种菜单结构(再次,基于缺乏信息的疯狂猜测),我正在更新上面的CSS来展示一个飞出式CSS菜单:< / p>

ul {
    /* adjust to taste */
    width: 6em;
}

ul ul {
    display: none;
    /* to more easily show the connection between the parent li and child ul
       adjust to taste, of course */
    background-color: inherit;
}

li {
    /* to position the child ul element relative to its parent */
    position: relative;
}

li:hover {
    /* just to identify which li element is currently hovered */
    background-color: #ffa;
}

li li:hover,
li:hover li:hover {
    /* so the hovered li is differentiated from its parent ul's background
       and the background of its grandparent li. Adjust to taste */
    background-color: #dda;
}

ul li:hover ul {
    /* so that it's visible on the page */
    display: block;
    position: absolute;
    /* to be level with its parents top-edge */
    top: 0;
    /* so that the li appears on the right of the parent li */
    left: 100%;
}​

JS Fiddle demo