使用场景

在项目上,时常需要对一些小图标进行颜色的修改。比如现在一张黑色的信息图标,但是项目里需要的是红色的,一般的做法是使用ps把图标颜色换成红色,如果另一个页面需要黄色的,就再做一张黄色的。。。。。。(无比麻烦)。。。。。。另一种方法就是把这个信息图标做成字体,引用进来。。。。。。(为了一个小图标要做一种字体,还不如第一种呢)。。。。。。

现在这一切都将变的简单,使用css3新属性filter中的drop-shadow,即可实现对png图标变换任意颜色。

原理

css3的filter有10种效果,点此了解。其中drop-shadow滤镜可以给元素或图片非透明区域添加投影。对于背景透明的png图标,我们只需要添加一个不模糊的投影,并对投影添加一个我们需要的颜色,然后对原图标实施平移,把投影移动原图标的位置就可以了。

代码

html:

1
2
3
4
<h3>原始图片</h3>
<div><i class="ws-icon icon-mes"></i></div>
<h3>变色图片</h3>
<div><i class="ws-icon"><i class="ws-icon icon-mes"></i></i></div>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
.icon-mes {
background: url(mes.png) no-repeat center;
}
.ws-icon {
display: inline-block;
width: 26px;
height: 24px;
overflow: hidden;
}
.ws-icon > .ws-icon {
/* 平移:第一种 */
/*
transform:translateX(-26px);
border-right: 26px solid transparent;
*/
/* 平移:第二种 */
width: 78px;
transform: translateX(-52px);
position: relative;
-webkit-filter: drop-shadow(rgba(63,136,204,.5) 26px 0);
filter: drop-shadow(rgba(63,136,204,.5) 24px 0);
cursor: pointer;
}

css代码里,其中最主要的就是drop-shadow(h-shadow v-shadow blur spread color),它有五个参数,具体使用方法及兼容性,请点此查看

对原图标的平移这里使用了两种,第一种是使用border的透明,将原图标平移到border的位置。第二种方法,设置投影的icon宽度为原图标的3倍,然后将原图标平移到投影区域之外。

html代码里,dom结构如果不想如此嵌套,也可以使用:after伪类来实现。如下
html:

1
2
3
4
<h3>原始图片</h3>
<div><i class="ws-icon icon-mes"></i></div>
<h3>使用:after实现</h3>
<div><i class="ws-icon-af icon-mes-af"></i></div>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.icon-mes-af:after {
background: url(mes.png) no-repeat center;
}
.ws-icon-af {
display: inline-block;
width: 26px;
height: 24px;
overflow: hidden;
position: relative;
}
.ws-icon-af:after{
content: "";
position: absolute;
height: 24px;
width: 78px;
left:0;
transform: translateX(-52px);
-webkit-filter: drop-shadow(rgba(63,136,204,.5) 26px 0);
filter: drop-shadow(rgba(63,136,204,.5) 24px 0);
}

实现的效果是相同的,dom结构更加简单。

实例

看实例,点此查看

本文地址: http://wsdever.github.io/2017/04/09/20170409/