【问题标题】:Hover one element, and change another (without using Javascript)悬停一个元素,然后更改另一个元素(不使用 Javascript)
【发布时间】:2011-12-11 13:38:03
【问题描述】:

我有一个嵌套的 CSS 菜单,我无法显示子菜单。

我从A list apart 获取代码。该站点上的示例运行良好,但由于我的页面上有 2 个 CSS 导航菜单,我必须将我的 HTML 元素放在不同的 CSS 类中。

这是我的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 

"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <style type="text/css">
    ul#lvl1 {
        margin:0;
        padding:0;
        list-style:none;
        width:150px; /* Width of Menu Items */
        border-bottom:1px solid #ccc;
    }
    li.lvl1 {position:relative}
    ul.lvl2 {
        position: absolute;
        left: 149px; /* Set 1px less than menu width */
        top: 0;
        display: none;
    }
    /* Styles for Menu Items */
    li.lvl1 > a {
      display: block;
        text-decoration: none;
        color: #777;
        background: #fff; /* IE6 Bug */
        padding: 5px;
        border: 1px solid #ccc;
        border-bottom: 0;
    }
    /* Fix IE. Hide from IE Mac \*/
    *  html.lvl1 > ul > li {float:left;height:1%}
    *  html.lvl1 > ul > li > a {height:1%}
    /* End */
    li.lvl2 > a:hover { color: #E2144A; background: #f9f9f9; } /* Hover Styles */
    li.lvl2 > a { padding: 2px 5px; } /* Sub Menu Styles */
    a.lvl1:hover ul.lvl2 {display: block} /* The magic */
  </style>
</head>
<body>
  <ul id="lvl1">
    <li class="lvl1">
      <a class="lvl1" href="#">item1</a>
      <ul class="lvl2">
        <li class="lvl2">
          <a class="lvl2" href="#">subitem1</a>
        </li>
      </ul>
    </li>
    <li class="lvl1">
      <a class="lvl1" href="#">item2</a>
      <ul class="lvl2">
        <li class="lvl2">
          <a class="lvl2" href="#">subitem2</a>
        </li>
      </ul>
    </li>
  </ul>
</body>
</html>

现在,当我将鼠标悬停在第 1 层的“a”上时,第 2 层的“ul”不会出现。有人可以阐明一下吗?我可能遗漏了一些明显的东西。谢谢!

【问题讨论】:

    标签: css hover


    【解决方案1】:

    您必须更改您的 CSS 选择器以定位 lvl2 &lt;ul&gt;,因为它不再嵌套(它是兄弟,所以使用 +)。

    a.lvl1:hover + ul.lvl2 {display: block} /* The magic */
    

    你应该阅读这个 list of css selectors.

    或者您可以将鼠标悬停在 lvl1 &lt;li&gt; 上,而不是锚点

    li.lvl1:hover ul.lvl2 {display: block} /* The magic */
    

    【讨论】:

    • 浏览对选择器的支持会有所不同。如果你需要支持 ie6 那就不要这样做了。
    • 可惜还需要支持ie6!
    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    相关资源
    最近更新 更多