【问题标题】:Transition doesn't work on pseudo-element过渡不适用于伪元素
【发布时间】:2015-11-03 20:18:03
【问题描述】:

我想在 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;
}

【问题讨论】:

标签: css css-transitions


【解决方案1】:

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

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

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

【讨论】:

  • 为什么会被否决?为什么问题和每个答案都被否决了?看起来有人在横冲直撞...
  • 我正在对旧答案大发雷霆:P。不过,这对我来说似乎是一个非常好的答案。
【解决方案2】:

这里有两个主要问题。首先,您要为锚元素添加过渡,而不是“::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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-22
    • 2016-02-13
    • 1970-01-01
    • 2021-04-26
    • 2019-03-26
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多