用神奇的currentColor制作简洁的颜色动画效果

时间:2023-03-08 17:19:35

先上一个兼容性总结图:老版本ie可以直接用复杂方法了,套用某表情包的话:

 2016年了,做前端你还考虑兼容IE6?你这简直是自暴自弃!

用神奇的currentColor制作简洁的颜色动画效果

好了,知道了兼容性,我们可以放心的使用了。

在CSS3中扩展了颜色值包含 currentColor 关键字,相当于元素color属性的计算值,让没有默认继承的子元素或者颜色属性可以继承。

用于所有接受颜色的属性上,相当于 color: inherit

如:background,可以设置background:currentColor,这样背景颜色就和页面当前的颜色一样了,background设置成inherit时,并不会使用当前颜色。

<div class="center">
  <div class="center_text">
我是文字文字文字
  </div>
</div>

  

.center_text{
border: 1px solid;
background: currentColor;
background-image: linear-gradient(to right, #fff, currentColor 100%);
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
}
.center{
  color:#000;
}

 当外层div设置颜色是#000时,显示如左图,当只把其颜色改成#bb1515时,会显示右侧。而渐变色是没有inherit的,这里我们可以使用currentColor,这样当我们想要换主题的时候,只要修改外层颜色即可。

用神奇的currentColor制作简洁的颜色动画效果用神奇的currentColor制作简洁的颜色动画效果

这种情况还以用在hover的时候,设置:

.center:hover{
  color: #bb5515;
}

用神奇的currentColor制作简洁的颜色动画效果

当鼠标hover在上面的时候,这里我们只需要控制最外层的颜色就行。

用这个属性可以方便简洁的实现很多美腻的效果。

1.用在伪元素上。

.center_text:after{
content:'';
width: 20px;
height: 20px;
display: inline-block;
background: currentColor;
vertical-align: middle; }

效果

用神奇的currentColor制作简洁的颜色动画效果用神奇的currentColor制作简洁的颜色动画效果

左图正常,右图hover时。

2.<hr>

代码:

.center{
color: #000;
}
.center:hover{
color: #bb5515;
}
.center_text{
border: 1px solid;
width: 400px;
height: 200px;
text-align: center;
}
.center_text hr{
background: currentColor;
height: 1px;
border:none;
}
<div class="center">
  <div class="center_text">
<p>在CSS3中扩展了颜色值包含 currentColor 关键字,相当于元素color属性的计算值,让没有默认继承的子元素或者颜色属性可以继承。用于所有接受颜色的属性上,相当于 color: inherit。</p>
<hr />
<p>如:background,可以设置background:currentColor,这样背景颜色就和页面当前的颜色一样了,background设置成inherit时,并不会使用当前颜色。</p>
</div>
</div>

效果

用神奇的currentColor制作简洁的颜色动画效果用神奇的currentColor制作简洁的颜色动画效果

左图正常,右图hover时。

3.元素中将会得到/继承元素color值的包括:

  • 元素的文本内容
  • 元素的边框、阴影、背景颜色
  • imgalt
  • 列表项的小黑点
  • hr
  • svg

总之currentColor可以使元素表现出当前元素的颜色,只修改最外层颜色就可以同时改变通过currentColor设置颜色属性的元素。非常方便。

有趣的实例:(打开等3s)

Demo