如何基于filter实现网站整体变灰功能
前言
政府网站会遇到公祭日的时候,网站整体颜色变灰的情况。今天正好调了一下。在此把解决方案分享给大家。方案简单实用,笔者已在生产环境使用过。通过整体的html使用filter来进行过滤。如下,只要引入即可。
解决方案
html{
filter:url("data:image/svg+xml;utf8,#grayscale");
-webkit-filter:grayscale(100%);
filter:grayscale(100%);
filter:gray;
filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
}
IE11和IE10的解决方案
经过测试发现,以上代码的方式对于谷歌,火狐,IE8,9都很好使。对于IE11和IE10效果不奏效。于是我们采取另一种方式,通过引用grayscale.js来使用。由于不能上传文件,在此将grayscale.js的代码写下来。
/*
*--grayscale.js--
*Copyright(C)JamesPadolsey(http://james.padolsey.com)
*Downloadby//www.nhooo.com
*/
vargrayscale=(function(){
varconfig={
colorProps:['color','backgroundColor','borderBottomColor','borderTopColor','borderLeftColor','borderRightColor','backgroundImage'],
externalImageHandler:{
/*Grayscalingexternallyhostedimagesdoesnotwork
-Usethesefunctionstohandlethoseimagesasyousodesire*/
/*Outofconveniencethesefunctionsarealsousedforbrowsers
likeChromethatdonotsupportCanvasContext.getImageData*/
init:function(el,src){
if(el.nodeName.toLowerCase()==='img'){
//IsIMGelement...
}else{
//Isbackground-imageelement:
//Default-removebackgroundimages
data(el).backgroundImageSRC=src;
el.style.backgroundImage='';
}
},
reset:function(el){
if(el.nodeName.toLowerCase()==='img'){
//IsIMGelement...
}else{
//Isbackground-imageelement:
el.style.backgroundImage='url('+(data(el).backgroundImageSRC||'')+')';
}
}
}
},
log=function(){
try{window.console.log.apply(console,arguments);}
catch(e){};
},
isExternal=function(url){
//CheckswhetherURLisexternal:'CanvasContext.getImageData'
//onlyworksiftheimageisonthecurrentdomain.
return(newRegExp('https?://(?!'+window.location.hostname+')')).test(url);
},
data=(function(){
varcache=[0],
expando='data'+(+newDate());
returnfunction(elem){
varcacheIndex=elem[expando],
nextCacheIndex=cache.length;
if(!cacheIndex){
cacheIndex=elem[expando]=nextCacheIndex;
cache[cacheIndex]={};
}
returncache[cacheIndex];
};
})(),
desatIMG=function(img,prepare,realEl){
//realElisonlysetwhenimgistemp(forBGimages)
varcanvas=document.createElement('canvas'),
context=canvas.getContext('2d'),
height=img.naturalHeight||img.offsetHeight||img.height,
width=img.naturalWidth||img.offsetWidth||img.width,
imgData;
canvas.height=height;
canvas.width=width;
context.drawImage(img,0,0);
try{
imgData=context.getImageData(0,0,width,height);
}catch(e){}
if(prepare){
desatIMG.preparing=true;
//Slowlyrecursethroughpixelsforprep,
//::onlyoccursongrayscale.prepare()
vary=0;
(function(){
if(!desatIMG.preparing){return;}
if(y===height){
//Finished!
context.putImageData(imgData,0,0,0,0,width,height);
realEl?(data(realEl).BGdataURL=canvas.toDataURL())
:(data(img).dataURL=canvas.toDataURL())
}
for(varx=0;x-1){
varurlPatt=/\(['"]?(.+?)['"]?\)/,
url=style.match(urlPatt)[1];
if(isExternal(url)){
config.externalImageHandler.init(cur,url);
data(cur).externalBG=true;
continue;
}
//data(cur).BGdataURLreferstocachesURL(frompreparation)
try{
varimgSRC=data(cur).BGdataURL||(function(){
vartemp=document.createElement('img');
temp.src=url;
returndesatIMG(temp).toDataURL();
})();
cur.style[prop]=style.replace(urlPatt,function(_,url){
return'('+imgSRC+')';
});
}catch(e){config.externalImageHandler.init(cur,url);}
}
}
}
}
};
init.reset=function(context){
//HandleifaDOMcollectionispassedinsteadofasingleel:
if(context&&context[0]&&context.length&&context[0].nodeName){
//IsaDOMcollection:
varallContexts=Array.prototype.slice.call(context),
cIndex=-1,cLen=allContexts.length;
while(++cIndex-1){
varurlPatt=/\(['"]?(.+?)['"]?\)/,
url=style.match(urlPatt)[1];
if(!isExternal(url)){
vartemp=document.createElement('img');
temp.src=url;
desatIMG(temp,true,cur);
}
}
}
}
};
returninit;
})();
使用方式如下,中心思想就是当我们是ie10和ie11浏览器的时候,调用graystyle的js函数。
varnavStr=navigator.userAgent.toLowerCase();
if(navStr.indexOf("msie10.0")!==-1||navStr.indexOf("rv:11.0")!==-1){//判断是IE10或者IE11
$(function(){
grayscale($('body'));
})
}
这里建议直接捕捉body,如果想针对某一个,换其中的捕捉元素就可以。
总结
至此,网站变灰的方案就完美了。完美兼容各种浏览器,笔者已经在生产环境使用过了,大家放心使用。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。