设计思路:
- 在btn按钮的前后都加上伪元素before和after元素(宽度为0,不显示出来)
- 为鼠标添加hover,当鼠标悬停上去的时候给伪元素都设置宽度为100%
- 为其中之一的伪元素增加过渡效果transition,并且设置背景颜色
- 另一个伪元素不用设置过渡,得到立马变化的效果
keys:
before和after一直在最下方
如果没有after的话会导致,btn的背景为透明会出现看着before从左到右变化
解决方法就是增加after元素,并且设置背景色与原先btn背景色一致
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.btn{
position: relative;
width: auto;
min-width: 120px;
padding: 10px;
text-align: center;
color: #fff;
background: #00d463;
cursor: pointer;
border-radius: 4px;
border: none;
}
.btn:after,.btn:before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 0;
height: 100%;
background: #00d463;
z-index:-2;
border-radius: 4px;
}
.btn:hover{
z-index:1;
background:transparent;
}
.btn:before {
transition: .3s;
background: #14ae5c;
z-index:-1;
}
.btn:hover:after,.btn:hover:before {
width: 100%;
}
</style>
</head>
<body>
<button class="btn">Try Free</button>
</body>
</html>
参考于 https://blog.youkuaiyun.com/ann295258232/article/details/90059607