css的图片换色属性

139 阅读1分钟

开发时发现有部分图片需要修改颜色或者是动态修改选中的颜色

想到的方法有四种

1.转成iconFont,

2.svg,

3.保存两张图片动态切换,

4.css的filter属性

第一种,如果是项目开发前期,转成iconfont比较方便,后面总不能一直让ui转吧,花费的时间成本还是比较高

第二种,svg的具体代码,实现起来还是很麻烦的

<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">
  <circle id="circle1" r="30" cx="34" cy="34" 
            style="fill: red; stroke: blue; stroke-width: 2"/>
  </svg>
<button onclick="circle1.style.fill='yellow';">Click to change to yellow</button>

第三种,v-show去动态切换,需要保存两张图片,如果是多个颜色就要保存多个图片去切换,还是比较麻烦

第四种,个人觉得还是最佳实现方式

原理:就是在div里面放一个img,div和img的宽高一定要设置一直,然后filter属性是颜色更换,将原图偏移上宽高的位置然后将其隐藏掉,展示修改颜色的图片

.style4-tabbar {
    width: 16px;
    height: 16px;
    text-indent: -16px;
    overflow: hidden;
    img {
      width: 16px;
      height: 16px;
      filter: drop-shadow(16px 0px var(--var-theme-color));
    }
  }