CSS 仅 - 如何在按钮悬停时滑出菜单?

CSS ONLY - how to slide out menu on button hover?

我希望当我将鼠标悬停在按钮上时菜单滑出。不知何故,只有当我将悬停效果添加到菜单本身而不是按钮时,它才会起作用。我在网上能找到的都是一样的(悬停效果附加到应该滑出的菜单,而不是按钮)。我该如何实施? jsfiddle: https://jsfiddle.net/codingcodingcoding/tuhug8x8/

html:

  <span class="glyphicon glyphicon-home icon" style="font-size:40px;z-index:2;"> </span>
  <nav id="navigation">
    <ul>
      <li>home</li>
      <li>home</li>
      <li>home</li>
    </ul>
  </nav>

css:

.icon:hover#navigation {
  left: 0;
}

.icon {
  left: 0px;
}

#navigation {
  position: fixed;
  width: 200px;
  height: 300px;
  background-color: red;
  top: 0;
  left: -200px;
}

#navigation 应该是图标容器(在您的例子中是 span 元素)的 子元素 ,以便能够 select 它悬停了。您只需移动结束 span 标签,如下所示。

(我在代码段中使用了图片而不是图标,但在 fiddle 中,您会看到图标:https://jsfiddle.net/qLy4g8sL/1/

.icon {
  left: 0px;
}

#navigation {
  position: absolute;
  width: 200px;
  height: 300px;
  background-color: red;
  top: 0;
  left: -200px;
}
.icon:hover #navigation {
  left: 0;
}
<span class="glyphicon glyphicon-home icon" style="font-size:40px;"><img src="http://placehold.it/50x50">
<nav id="navigation">
  <ul>
    <li>home</li>
    <li>home</li>
    <li>home</li>
  </ul>
</nav>
</span>

如果您想保持当前的 HTML 结构,您可以使用 + 或 ~ CSS 选择器:

.icon:hover + #navigation {
  left: 0;
}

.icon {
  left: 0px;
}

#navigation {
  position: fixed;
  width: 200px;
  height: 300px;
  background-color: red;
  top: 0;
  left: -200px;
}
<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<span class="glyphicon glyphicon-home icon" style="font-size:40px;z-index:2;"> </span>
<nav id="navigation">
  <ul>
    <li>home</li>
    <li>home</li>
    <li>home</li>
  </ul>
</nav>

你可以read more about

html

<span class="glyphicon glyphicon-home icon" style="font-size:40px;z-index:2;"> </span>
  <nav id="navigation">
    <ul>
      <li>home</li>
      <li>home</li>
      <li>home</li>
    </ul>
  </nav>

css:

.icon:hover + #navigation {
  left: 0;
}

.icon {
  left: 0px;
}

#navigation {
  position: fixed;
  width: 200px;
  height: 300px;
  background-color: red;
  top: 0;
  left: -200px;
}

在这里,我只添加了 + 选择器 olny。