灰色滤镜的使用及兼容方案
1. 需求:
现在一般的主流网站及政府网站,在国家公祭日的时候都会进行全网置灰或者首页置灰。针对现有项目需求进行总结一下。
2. 代码
html,img{
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: grayscale(100%);
filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0'/></filter></svg>#grayscale");
filter: progid: DXImageTransform.Microsoft.BasicImage(grayscale=1);
filter: gray;
}
这样设置可以将全网变灰,但关于一些政府网站要兼容各种浏览器,此属性不兼容IE10,IE11所以针对IE要做针对性处理
3.兼容IE11,IE10
<script type="text/javascript" src="grayscale.js"></script>
<script type="text/javascript">
// 判断浏览器版本
var navStr = navigator.userAgent.toLowerCase();
if(navStr.indexOf("msie 10.0")!==-1||navStr.indexOf("rv:11.0")!==-1){
// 判断是IE10或者IE11
grayscale(document.body);
}
</script>
- 封装图片置灰组件
<template>
<div>
<img :src="src" alt="" :width="currentWidth" :height="currentHeight" v-if="!IeFilterValue" :class="calssName">
<svg v-else overflow="visible" :width="width" :height="height" :viewBox="viewBox" preserveAspectRatio="none slice" >
<image overflow="visible" preserveAspectRatio="none slice" xmlns:xline="http://www.w3.org/1999/xlink" :xlink:href="src" x="0" y="0" :width="width" :height="height" filter=url('#grayscale') /></image>
</svg>
</div>
</template>
<script>
export default {
name: "img-box",
data() {
return {
};
},
props:{
src:String,className:String,width:String,height:String},
computed:{
viewBox(){
return('0 0 '+this.filterPx(this.width)+' '+this.filterPx(this.height))
}
},
IeFilterValue(){
return this.$store.state.app.IeFilterValue;
},
currentWidth(){
return this.filterNumber(this.width)
},
currentHeight(){
return this.filterNumber(this.heigth)
},
created(){
},
methods:{
filterPx(val){
return val&&val.replace? val.replace('px',''):val},
filterNumber(val){
if(!val) return ""
return String(val)
}
};
</script>