css3 让图片变成灰色(filter),但针对IE11浏览器无效
问题描述
想要设置网站图片默认为灰色,鼠标经过时显示为彩色
在网上找了很多方法, 修改css后,在非IE浏览器内都可以正常显示为灰色,但在IE11浏览器内一直为彩色查看好多教程,说是IE6-9都可以,但更高版本就不行了,有什么好办法没有
代码如下:
{-webkit-filter: grayscale(1);-moz-filter: grayscale(1);filter: grayscale(1);-ms-filter: grayscale(1);-o-filter: grayscale(1);filter: gray;}
请各位帮忙看看是什么原因
问题解答
回答1:如果不是svg的图片格式,filter在ie浏览器上都不支持。如果是svg的话,filter也只是在ie10和11上支持。详细见caniuse
回答2:可能是当前的IE版本不兼容部分CSS3属性哦
回答3:svg或者canvas
回答4:可以使用canvas
var imgObj = document.getElementById(’imgToGray’); function gray(imgObj) { var canvas = document.createElement(’canvas’); var canvasContext = canvas.getContext(’2d’);var imgW = imgObj.width; var imgH = imgObj.height; canvas.width = imgW; canvas.height = imgH;canvasContext.drawImage(imgObj, 0, 0); var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);for (var y = 0; y < imgPixels.height; y++) { for (var x = 0; x < imgPixels.width; x++) { var i = (y * 4) * imgPixels.width + x * 4; var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; imgPixels.data[i] = avg; imgPixels.data[i + 1] = avg; imgPixels.data[i + 2] = avg; } } canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); return canvas.toDataURL(); } imgObj.src = gray(imgObj);