SoFunction
Updated on 2025-03-10

How to implement the overall graying function of the website based on filter

Preface

The website will encounter the overall color of the website turning gray during the public memorial day. I happened to adjust it today. Here we share the solution with you. The solution is simple and practical, and I have used it in the production environment. Filter through the overall html. As follows, just introduce it.

Solution

html { 
  filter: url("data:image/svg+xml;utf8,#grayscale"); 
  -webkit-filter: grayscale(100%); 
  filter: grayscale(100%); 
  filter: gray; 
  filter:progid:(grayscale=1);
}

IE11 and IE10 solutions

After testing, it was found that the above code method is very easy for Google, Firefox, IE8, and 9. The effect does not work for IE11 and IE10. So we take another way, using it by reference. Since the file cannot be uploaded, write down the code here.

/*
 * --  --
 * Copyright (C) James Padolsey ()
 * Download by //
 */

var grayscale = (function(){
  
  var config = {
      colorProps: ['color','backgroundColor','borderBottomColor','borderTopColor','borderLeftColor','borderRightColor','backgroundImage'],
      externalImageHandler : {
        /* Grayscaling externally hosted images does not work
          - Use these functions to handle those images as you so desire */
        /* Out of convenience these functions are also used for browsers
          like Chrome that do not support  */
        init : function(el, src) {
          if (() === 'img') {
            // Is IMG element...
          } else {
            // Is background-image element:
            // Default - remove background images
            data(el).backgroundImageSRC = src;
             = '';
          }
        },
        reset : function(el) {
          if (() === 'img') {
            // Is IMG element...
          } else {
            // Is background-image element:
             = 'url(' + (data(el).backgroundImageSRC || '') + ')';
          }
        }
      }
    },
    log = function(){
      try { (console, arguments); }
      catch(e) {};
    },
    isExternal = function(url) {
      // Checks whether URL is external: ''
      // only works if the image is on the current domain.
      return (new RegExp('https?://(?!' +  + ')')).test(url);
    },
    data = (function(){
      
      var cache = [0],
      expando = 'data' + (+new Date());
      
      return function(elem) {
        var cacheIndex = elem[expando],
          nextCacheIndex = ;
        if(!cacheIndex) {
          cacheIndex = elem[expando] = nextCacheIndex;
          cache[cacheIndex] = {};
        }
        return cache[cacheIndex];
      };
      
    })(),
    desatIMG = function(img, prepare, realEl) {
      
      // realEl is only set when img is temp (for BG images)
      
      var canvas = ('canvas'),
        context = ('2d'),
        height =  ||  || ,
        width =  ||  || ,
        imgData;
        
       = height;
       = width;
      (img, 0, 0);
      try {
        imgData = (0, 0, width, height);
      } catch(e) {}
      
      if (prepare) {
         = true;
        // Slowly recurse through pixels for prep,
        // :: only occurs on ()
        var y = 0;
        (function(){
          
          if (!) { return; }
          
          if (y === height) {
            // Finished!
            (imgData, 0, 0, 0, 0, width, height);
            realEl ? (data(realEl).BGdataURL = ())
                : (data(img).dataURL = ())
          }
          
          for (var x = 0; x < width; x++) {
            var i = (y * width + x) * 4;
            // Apply Monoschrome level across all channels:
            [i] = [i+1] = [i+2] =
            RGBtoGRAYSCALE([i], [i+1], [i+2]);
          }
          
          y++;
          setTimeout(, 0);
          
        })();
        return;
      } else {
        // If desatIMG was called without 'prepare' flag
        // then cancel recursion and proceed with force! (below)
         = false;
      }
      
      for (var y = 0; y < height; y++) {
        for (var x = 0; x < width; x++) {
          var i = (y * width + x) * 4;
          // Apply Monoschrome level across all channels:
          [i] = [i+1] = [i+2] =
          RGBtoGRAYSCALE([i], [i+1], [i+2]);
        }
      }
      
      (imgData, 0, 0, 0, 0, width, height);
      return canvas;
    
    },
    getStyle = function(el, prop) {
      var style =  &&  ? 
            (el, null)[prop]
            : [prop];
      // If format is #FFFFFF: (convert to RGB)
      if (style && /^#[A-F0-9]/(style)) {
          var hex = (/[A-F0-9]{2}/ig);
          style = 'rgb(' + parseInt(hex[0], 16) + ','
                  + parseInt(hex[1], 16) + ','
                  + parseInt(hex[2], 16) + ')';
      }
      return style;
    },
    RGBtoGRAYSCALE = function(r,g,b) {
      // Returns single monochrome figure:
      return parseInt( (0.2125 * r) + (0.7154 * g) + (0.0721 * b), 10 );
    },
    getAllNodes = function(context) {
      var all = (('*'));
      (context);
      return all;
    };
    
  var init = function(context) {
    
    // Handle if a DOM collection is passed instead of a single el:
    if (context && context[0] &&  && context[0].nodeName) {
      // Is a DOM collection:
      var allContexts = (context),
        cIndex = -1, cLen = ;
      while (++cIndex<cLen) { (this, allContexts[cIndex]); }
      return;
    }
    
    context = context || ;
    
    if (!('canvas').getContext) {
       = 'progid:(grayscale=1)';
       = 1;
      return;
    }
    
    var all = getAllNodes(context),
      i = -1, len = ;
      
    while (++i<len) {
      var cur = all[i];
      
      if (() === 'img') {
        var src = ('src');
        if(!src) { continue; }
        if (isExternal(src)) {
          (cur, src);
        } else {
          data(cur).realSRC = src;
          try {
            // Within try statement just encase there's no support....
             = data(cur).dataURL || desatIMG(cur).toDataURL();
          } catch(e) { (cur, src); }
        }
        
      } else {
        for (var pIndex = 0, pLen = ; pIndex < pLen; pIndex++) {
          var prop = [pIndex],
          style = getStyle(cur, prop);
          if (!style) {continue;}
          if ([prop]) {
            data(cur)[prop] = style;
          }
          // RGB color:
          if ((0,4) === 'rgb(') {
            var monoRGB = (null, (/\d+/g));
            [prop] = style = 'rgb(' + monoRGB + ',' + monoRGB + ',' + monoRGB + ')';
            continue;
          }
          // Background Image:
          if (('url(') > -1) {
            var urlPatt = /\(['"]?(.+?)['"]?\)/,
              url = (urlPatt)[1];
            if (isExternal(url)) {
              (cur, url);
              data(cur).externalBG = true;
              continue;
            }
            // data(cur).BGdataURL refers to caches URL (from preparation)
            try {
              var imgSRC = data(cur).BGdataURL || (function(){
                  var temp = ('img');
                   = url;
                  return desatIMG(temp).toDataURL();
                })();
              
              [prop] = (urlPatt, function(_, url){
                return '(' + imgSRC + ')';
              });
            } catch(e) { (cur, url); }
          }
        }
      }
    }
    
  };
  
   = function(context) {
    // Handle if a DOM collection is passed instead of a single el:
    if (context && context[0] &&  && context[0].nodeName) {
      // Is a DOM collection:
      var allContexts = (context),
        cIndex = -1, cLen = ;
      while (++cIndex<cLen) { (this, allContexts[cIndex]); }
      return;
    }
    context = context || ;
    if (!('canvas').getContext) {
       = 'progid:(grayscale=0)';
      return;
    }
    var all = getAllNodes(context),
      i = -1, len = ;
    while (++i<len) {
      var cur = all[i];
      if (() === 'img') {
        var src = ('src');
        if (isExternal(src)) {
          (cur, src);
        }
         = data(cur).realSRC || src;
      } else {
        for (var pIndex = 0, pLen = ; pIndex < pLen; pIndex++) {
          if (data(cur).externalBG) {
            (cur);
          }
          var prop = [pIndex];
          [prop] = data(cur)[prop] || '';
        }
      }
    }
  };
  
   = function(context) {
    
    // Handle if a DOM collection is passed instead of a single el:
    if (context && context[0] &&  && context[0].nodeName) {
      // Is a DOM collection:
      var allContexts = (context),
        cIndex = -1, cLen = ;
      while (++cIndex<cLen) { (null, allContexts[cIndex]); }
      return;
    }
    
    // Slowly recurses through all elements
    // so as not to lock up on the user.
    
    context = context || ;
    
    if (!('canvas').getContext) { return; }
    
    var all = getAllNodes(context),
      i = -1, len = ;
    
    while (++i<len) {
      var cur = all[i];
      if (data(cur).skip) { return; }
      if (() === 'img') {
        if (('src') && !isExternal()) {
          desatIMG(cur, true);
        }
        
      } else {
        var style = getStyle(cur, 'backgroundImage');
        if (('url(') > -1) {
          var urlPatt = /\(['"]?(.+?)['"]?\)/,
            url = (urlPatt)[1];
          if (!isExternal(url)) {
            var temp = ('img');
             = url;
            desatIMG(temp, true, cur);
          }
        }
      }
    }
  };
  
  return init;

})();
How to use it is as follows,The central idea is to think we areie10andie11When in the browser,Callgraystyleofjsfunction。

<script type="text/javascript">
 var navStr = ();
 if(("msie 10.0")!==-1||("rv:11.0")!==-1){ // Determine IE10 or IE11  $(function () {
    grayscale($('body'));
  })
 }
</script>

It is recommended to directly capture the body. If you want to target a certain one, just change the capture element in it.

Summarize

At this point, the solution to the website's graying is perfect. Perfectly compatible with various browsers, the author has used it in the production environment, so everyone can use it with confidence.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.