悬停时不触发过渡

Transition not firing on hover

我正在尝试实现一个滑动侧边栏,当用户将鼠标悬停在 .sb-toggle 项目上时该侧边栏会激活。将鼠标悬停在它上面会导致位于视图外的侧边栏以 10em 的速度滑动,同时也会使 .content div 向右移动。但我无法让它正常工作。 .sb-toggle.content 项目会触发过渡,但不会显示边栏。

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.navbar {
  z-index: 1;
  position: fixed;
  top: 0%;
  background-color: #333;
  height: 3em;
  width: 100%;
  overflow: hidden;
  border-bottom: 1px solid grey;
}

.sidebar {
  background-color: #404040;
  width: 10em;
  height: 100%;
  position: fixed;
  margin-left: -10em;
  top: 3em;
  bottom: 0;
  -moz-transition: margin-left 0.5s ease;
  transition: margin-left 0.5s ease-in-out;
}

.sb-toggle {
  background-color: #404040;
  width: 1.5em;
  height: 100%;
  position: fixed;
  top: 3em;
  left: 0;
  -moz-transition: margin-left 0.5s ease;
  transition: margin-left 0.5s ease-in-out;
}

.content {
  margin-top: 3em;
  margin-left: 10em;
  height: inherit;
  width: inherit;
  transition: margin-left 0.5s ease-in-out;
}

.sb-toggle:hover {
  margin-left: 10em;
}

.sb-toggle:hover ~ .sidebar {
  margin-left: 0;
}

.sb-toggle:hover ~ .content {
  margin-left: 20em;
}

编辑:这是 HTML:

<body>
    <div class="navbar"></div>
    <div class="sidebar"></div>
    <div class="sb-toggle"></div>
    <div class="content"></div>
  </body>

您需要明确指定起点和终点。

例如:

.sb-toggle {
  /* other stuff */
  margin-left: 0; /* <-- You need to add this */
  -moz-transition: margin-left 0.5s ease;
  transition: margin-left 0.5s ease-in-out;
}

.sb-toggle div 放在 .sidebar 中,并将 :hover.sb-toggle 更改为 .sidebar

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.navbar {
  z-index: 1;
  position: fixed;
  top: 0%;
  background-color: #333;
  height: 3em;
  width: 100%;
  overflow: hidden;
  border-bottom: 1px solid grey;
}

.sidebar {
  background-color: #404040;
  width: 10em;
  height: 100%;
  position: fixed;
  margin-left: -10em;
  top: 3em;
  bottom: 0;
  -moz-transition: margin-left 0.5s ease;
  transition: margin-left 0.5s ease-in-out;
}

.sb-toggle {
  background-color: #404040;
  width: 1.5em;
  height: 100%;
  position: fixed;
  top: 3em;
  left: 0;
  -moz-transition: margin-left 0.5s ease;
  transition: margin-left 0.5s ease-in-out;
}

.content {
  margin-top: 3em;
  margin-left: 10em;
  height: inherit;
  width: inherit;
  transition: margin-left 0.5s ease-in-out;
}

.sb-toggle:hover {
  margin-left: 10em;
}

.sidebar:hover {
  margin-left: 0;
}

.sidebar:hover ~ .content {
  margin-left: 20em;
}
<body>
    <div class="navbar"></div>
    <div class="sidebar">
     <div class="sb-toggle"></div>
    </div>
   
    <div class="content"></div>
  </body>

兄弟选择器 ~ 只在 DOM 中向前看,而不是向后看。 因此 .sb-toggle ~ .sidebar 行永远不会被执行。

来自 MDN 文档:

"The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent."

制作了一个小演示来展示上述行为: https://codepen.io/anon/pen/jREMmb

您要么必须交换 DOM 个节点的顺序,要么找到另一条路线来触发转换