过渡不会在悬停时触发

时间:2019-04-01 13:32:21

标签: css transition

我正在尝试实现一个滑动边栏,当用户将鼠标悬停在.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>

3 个答案:

答案 0 :(得分:1)

.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>

答案 1 :(得分:0)

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

例如:

.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;
}

答案 2 :(得分:0)

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

来自MDN文档:

“〜组合器选择同级。这意味着第二个元素紧随第一个(尽管不一定紧随其后),并且都共享相同的父元素。”

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

您要么必须交换DOM节点的顺序,要么需要找到另一条路由来触发过渡

相关问题