This question already has answers here:
Color to grayscale on hover not working in IE11
                                
                                    (2个答案)
                                
                        
                                4个月前关闭。
            
                    
我想使用灰度将整个页面设为黑白。它在所有需要IE 11的浏览器中也能很好地工作。有许多类似的问题,但通常针对特定元素like an image

我有以下代码:

body {
  width: 100%;
  filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
  -webkit-filter: grayscale(1);
  filter: grayscale(1);
}


因此效果很好,整个页面都是黑白的。我如何才能为IE11完成此操作?有没有合理的技巧?

问题与建议的答案不同->我正在这里寻找一种解决方案,如何以某种合理的方式克服IE中的问题。

最佳答案

由于IE不支持滤镜:灰度,因此您可以尝试使用SVG + JS方法在IE中应用灰度滤镜。

以下是代码片段的一部分。

// Grayscale images only on browsers IE10+ since they removed support for CSS grayscale filter
if (getInternetExplorerVersion() >= 10){
    $('img').each(function(){
        var el = $(this);
        el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({"position":"absolute","z-index":"5","opacity":"0"}).insertBefore(el).queue(function(){
        var el = $(this);
        el.parent().css({"width":this.width,"height":this.height});
        el.dequeue();
    });
this.src = grayscaleIE10(this.src);
});

// Quick animation on IE10+
    $('img').hover(function () {
        $(this).parent().find('img:first').stop().animate({opacity:1}, 200);
    },
    function () {
        $('.img_grayscale').stop().animate({opacity:0}, 200);
    }
);

function grayscaleIE10(src){
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var imgObj = new Image();
    imgObj.src = src;
    canvas.width = imgObj.width;
    canvas.height = imgObj.height;
    ctx.drawImage(imgObj, 0, 0);
    var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
    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;
         }
     }
    ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
    return canvas.toDataURL();
    };
};


完整示例代码的参考:

Cross-Browser Grayscale image example using CSS3 + JS

IE 11中的输出:

css - 在IE11中过滤html/body元素的灰度-LMLPHP

关于css - 在IE11中过滤html/body元素的灰度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57422908/

10-13 01:36