过渡不适用于伪元素

Transition doesn't work on pseudo-element

我想在CSS3中使用过渡效果,但效果不起作用。 我想我可能犯了一个错误,但我没有看到它在哪里。

悬停时,我想在之前的伪元素中制作一个带过渡的边框。我做了一个代码笔:http://codepen.io/Tef/pen/JYBMgR

<div class="container wrap">
<div class="row">
    <div class="box">
        <a href="#">
            <img src="http://placehold.it/90x90/000000" alt="" />
        </a>
    </div>
</div>
</div>

.wrap {
  margin-top: 50px;
}
.wrap a {
  position: relative;
  display: inline-block;
  -webkit-transition: all 1s;
  -moz-transition: all 1s;
  -o-transition: all 1s;
  -ms-transition: all 1s;
  transition: all 1s;
}
.wrap a:hover:before {
  content: '';
  border: 7px solid #ffffff;
  opacity: .7;
  width: 90px;
  height: 90px;
  position: absolute;
  left: 0;
  top: 0;
}

这里有两个主要问题。首先,您要向锚元素添加过渡,而不是“::before”伪元素。其次,您没有为伪元素设置任何初始状态,而是将所有内容设置为悬停状态。如果你想转换你需要一个初始状态和一个结束状态。例如:

.wrap {
    margin-top: 50px;
    a {
        position: relative;
        display: inline-block;

        &::before{
            -webkit-transition: all 1s;
            -moz-transition: all 1s;
            -o-transition: all 1s;
            -ms-transition: all 1s;
            transition: all 1s;
            content: '';
            border: 0 solid #ffffff;
            opacity: 0;
            width: 90px;
            height: 90px;
            position: absolute;
            left: 0;
            top: 0;
        }

        &:hover {
            &::before {
                border: 7px solid #ffffff;
                opacity: .7;
            }
        }

    }
}

注意过渡是在伪元素上,我已经为这个元素的初始状态设置了初始值(不透明度:0 + 边框:0)

您的代码中存在一些问题:

  1. :before 仅存在于 :hover,但它应该始终存在以显示动画。
  2. transitiona 上定义,但实际上应该在 a:before 上(这在概念上是不同的 DOM 元素)。
  3. 边框没有初始状态,因此悬停时的过渡将以默认值开始,取消悬停时向后过渡将不起作用。要解决这个问题,只需添加一个初始边界状态,如 0px solid transparent.

这是您的固定示例:http://codepen.io/anon/pen/wKxmvB