首页 > 解决方案 > 使用 :after 属性后无法为按钮设置动画

问题描述

我试图让我的头脑围绕伪元素,但似乎无法获得一个简单的按钮动画来使用它。

悬停时,我希望面板从下到上。类似于此页面上的按钮(第 1 行,第 2 个按钮)。

据我了解, using会在每节课.btn:after添加任何 CSS 。但是为什么这不起作用呢?.btn

.btn {
    border: 1px solid #65bb39;
    color: #fff;
    background-color: #65bb39;
    cursor: pointer;
    padding: 25px 80px;
    display: inline-block;
    margin: 15px 30px;
    text-transform: uppercase;
    outline: none;
    position: relative;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
}
.btn:after {
    content: '';
    position: absolute;
    z-index: -1;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
    border: 1px solid #65bb39;
    background-color: #fff;
}
*, *:after, *:before {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
<div class="text">
  <span class="btn">Test</span>
</div>

悬停时,我希望边框转动#65bb39并且块填充白色(从下到上)。

当然,任何反馈beforeafter赞赏!

标签: htmlcss

解决方案


因此需要向 btn:after 添加悬停状态,然后在两种状态之间转换 css。请参阅下面的片段。

*, *:after, *:before {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}


.btn {
    color: #fff;
    cursor: pointer;
    padding: 25px 80px;
    display: inline-block;
    margin: 15px 30px;
    text-transform: uppercase;
    position: relative;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
}

.btn:hover{
    color: #65bb39;
}

.btn:after, .btn:before {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 0;
    color: #65bb39;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
    border: 1px solid #65bb39;
    background-color: #fff;
}

.btn:before {
  z-index: -2;
  background-color: #65bb39;
  height: 100%;
}

.btn:after {
  z-index: -1;
}

.btn:hover:after {    
    height: 100%;
}
<div class="btn">Test</div>


推荐阅读