元素前伪的 mouseout 过渡宽度

Transition width on mouseout for pseudo before element

我有一个 before 伪元素,当另一个元素悬停在上面时,我试图转换它的宽度。

Link 到 jsFiddle here

我似乎能够在元素的鼠标悬停时转换宽度,但在鼠标离开时我无法转换回 0px 的宽度。

编辑

我想我解释了我试图以错误的方式做的事情。请参阅下面的更新代码和 jsFiddle。我有一个父项目,当鼠标悬停在上面时,我需要子元素的 :before 元素的宽度来过渡。

<div class="hover">
   <div class="transition"></div>
</div>

.hover {
  width: 50px;
  height: 50px;
  background-color: #000;
}      

.transition:before {
  content: '';
  position: absolute;
 width: 0px;
 height: 0px;
 top: -10px;
 right: 100%;
 background-color: #d3d;
 z-index: -1;
 -webkit-transition: width 2s;
 transition: width 2s;
}

.hover:hover .transition:before {
 content: '';
 position: absolute;
 width: 125px;
 height: 70px;
 top: -10px;
 right: 94%;
 background-color: #d3d;
 -webkit-transition: width 2s;
 transition: width 2s;
}

我优化改改你的css。我希望它可以帮助你。 Jsfiddle

.transition {
  width: 50px;
  height: 50px;
  background-color: #000;
    position: relative;
}      

.transition:before {
  content: '';
  position: absolute;
  width: 0px;
  height: 0px;
  top: 0;
  left: 0;
  background-color: #d3d;
  z-index: -1;
  -webkit-transition: width 2s;
  transition: 2s;
}

.transition:hover:before {
  width: 125px;
  height: 70px;
    transition: 2s;
}
<div class="transition"></div>

主要是定位问题。宽度实际上是动画,但悬停时元素的定位将其从视口中移除。

为了在其父元素的上下文中绝对定位元素,必须定位父元素。使用 position: relative 是实现此目的的一种快速简便的方法,但在其他方面保持元素不变。另外,如果你只想在悬停时改变宽度,只改变宽度。

我仍然不确定你的目标是什么,但我的代码片段应该主要重现你用动画显示悬停和悬停实现的设计。

.hover { display: inline-block; }

.transition {
    position: relative;
    width: 50px;
    height: 50px;
    background-color: #000;
}

.transition::before {
    content: "";
    position: absolute;
    width: 0px;
    height: 70px;
    top: -10px;
    right: 0px;
    background-color: #d3d;
    z-index: -1;
    -webkit-transition: width 2s;
    transition: width 2s;
}

.hover:hover > .transition::before { width: 125px; }
<div class="hover">
   <div class="transition"></div>
</div>