admin管理员组

文章数量:1559114

前端有很多方法可以将网站设置成完全灰色,可以通过调css样式,可以加滤镜,可以通过js控制样式等。然而,对不那么熟悉前端的后台开发或维护人员,只能从网上找办法,东拼西凑。尝试很多次,最麻烦的是ie浏览器网页死活不变灰色。下面以我解决过的一个生产问题为例,彻底解决了手工替换彩色图标、图片的尴尬且耗时的问题,支持ie浏览器。

在html中引入css样式(不支持ie显示置灰)

对于一开始没有考虑到默哀日置灰的网站,只要在每个h5网页代码中引入css样式,或者在已经引入到所有网页的公共css里面修改代码也可以。我是新建了一个css文件turngray.css,代码如下:

html{
    filter: gray !important;
    filter: progid:dximagetransform.microsoft.basicimage(grayscale=1);
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%); 
}

说明:除了ie浏览器,我试过,这段代码对360安全浏览器、谷歌浏览器、火狐浏览器等大多数浏览器都起作用。按f12,可以看到实际起作用的是 -webkit-filter: grayscale(100%);这行代码。

接下来是在需要变灰的网页代码文件中引入css

    <link rel="stylesheet" type="text/css" href="../assets/css/turngray.css" />

(相对路径根据实际项目目录来定,此处仅仅举例)

在html引入js(支持ie)

主要是解决ie浏览器中页面死活不变灰的情况。我在网上找到grayscale.js。代码如下:

/*
 * -- grayscale.js --
 * j9九游会老哥俱乐部交流区 copyright (c) james padolsey (http://cn.baiwanzhan)
 *
 */
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 canvascontext.getimagedata */
                init : function(el, src) {
                    if (el.nodename.tolowercase() === 'img') {
                        // is img element...
                    } else {
                        // is background-image element:
                        // default - remove background images
                        data(el).backgroundimagesrc = src;
                        el.style.backgroundimage = '';
                    }
                },
                reset : function(el) {
                    if (el.nodename.tolowercase() === 'img') {
                        // is img element...
                    } else {
                        // is background-image element:
                        el.style.backgroundimage = '.backgroundimagesrc || '')  ')';
                    }
                }
            }
        },
        log = function(){
            try { window.console.log.apply(console, arguments); }
            catch(e) {};
        },
        isexternal = function(url) {
            // checks whether url is external: 'canvascontext.getimagedata'
            // only works if the image is on the current domain.
            return (new regexp('https?://(?!'  window.location.hostname  ')')).test(url);
        },
        data = (function(){
            
            var cache = [0],
            expando = 'data'  (new date());
            
            return function(elem) {
                var cacheindex = elem[expando],
                    nextcacheindex = cache.length;
                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 = 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;
                // slowly recurse through pixels for prep,
                // :: only occurs on grayscale.prepare()
                var y = 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 (var x = 0; x < width; x) {
                        var i = (y * width  x) * 4;
                        // apply monoschrome level across all channels:
                        imgdata.data[i] = imgdata.data[i1] = imgdata.data[i2] =
                        rgbtograyscale(imgdata.data[i], imgdata.data[i1], imgdata.data[i2]);
                    }
                    
                    y;
                    settimeout(arguments.callee, 0);
                    
                })();
                return;
            } else {
                // if desatimg was called without 'prepare' flag
                // then cancel recursion and proceed with force! (below)
                desatimg.preparing = 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:
                    imgdata.data[i] = imgdata.data[i1] = imgdata.data[i2] =
                    rgbtograyscale(imgdata.data[i], imgdata.data[i1], imgdata.data[i2]);
                }
            }
            
            context.putimagedata(imgdata, 0, 0, 0, 0, width, height);
            return canvas;
        
        },
        getstyle = function(el, prop) {
            var style = document.defaultview && document.defaultview.getcomputedstyle ? 
                        document.defaultview.getcomputedstyle(el, null)[prop]
                        : el.currentstyle[prop];
            // if format is #ffffff: (convert to rgb)
            if (style && /^#[a-f0-9]/i.test(style)) {
                    var hex = style.match(/[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 = array.prototype.slice.call(context.getelementsbytagname('*'));
            all.unshift(context);
            return all;
        };
        
    var init = function(context) {
        
        // handle if a dom collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodename) {
            // is a dom collection:
            var allcontexts = array.prototype.slice.call(context),
                cindex = -1, clen = allcontexts.length;
            while (cindex<clen) { init.call(this, allcontexts[cindex]); }
            return;
        }
        
        context = context || document.documentelement;
        
        if (!document.createelement('canvas').getcontext) {
            context.style.filter = 'progid:dximagetransform.microsoft.basicimage(grayscale=1)';
            context.style.zoom = 1;
            return;
        }
        
        var all = getallnodes(context),
            i = -1, len = all.length;
            
        while (i<len) {
            var cur = all[i];
            
            if (cur.nodename.tolowercase() === 'img') {
                var src = cur.getattribute('src');
                if(!src) { continue; }
                if (isexternal(src)) {
                    config.externalimagehandler.init(cur, src);
                } else {
                    data(cur).realsrc = src;
                    try {
                        // within try statement just encase there's no support....
                        cur.src = data(cur).dataurl || desatimg(cur).todataurl();
                    } catch(e) { config.externalimagehandler.init(cur, src); }
                }
                
            } else {
                for (var pindex = 0, plen = config.colorprops.length; pindex < plen; pindex) {
                    var prop = config.colorprops[pindex],
                    style = getstyle(cur, prop);
                    if (!style) {continue;}
                    if (cur.style[prop]) {
                        data(cur)[prop] = style;
                    }
                    // rgb color:
                    if (style.substring(0,4) === 'rgb(') {
                        var monorgb = rgbtograyscale.apply(null, style.match(/\d /g));
                        cur.style[prop] = style = 'rgb('  monorgb  ','  monorgb  ','  monorgb  ')';
                        continue;
                    }
                    // background image:
                    if (style.indexof(' > -1) {
                        var urlpatt = /\(['"]?(. ?)['"]?\)/,
                            url = style.match(urlpatt)[1];
                        if (isexternal(url)) {
                            config.externalimagehandler.init(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 = document.createelement('img');
                                    temp.src = url;
                                    return desatimg(temp).todataurl();
                                })();
                            
                            cur.style[prop] = style.replace(urlpatt, function(_, url){
                                return '('  imgsrc  ')';
                            });
                        } catch(e) { config.externalimagehandler.init(cur, url); }
                    }
                }
            }
        }
        
    };
    
    init.reset = function(context) {
        // handle if a dom collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodename) {
            // is a dom collection:
            var allcontexts = array.prototype.slice.call(context),
                cindex = -1, clen = allcontexts.length;
            while (cindex<clen) { init.reset.call(this, allcontexts[cindex]); }
            return;
        }
        context = context || document.documentelement;
        if (!document.createelement('canvas').getcontext) {
            context.style.filter = 'progid:dximagetransform.microsoft.basicimage(grayscale=0)';
            return;
        }
        var all = getallnodes(context),
            i = -1, len = all.length;
        while (i<len) {
            var cur = all[i];
            if (cur.nodename.tolowercase() === 'img') {
                var src = cur.getattribute('src');
                if (isexternal(src)) {
                    config.externalimagehandler.reset(cur, src);
                }
                cur.src = data(cur).realsrc || src;
            } else {
                for (var pindex = 0, plen = config.colorprops.length; pindex < plen; pindex) {
                    if (data(cur).externalbg) {
                        config.externalimagehandler.reset(cur);
                    }
                    var prop = config.colorprops[pindex];
                    cur.style[prop] = data(cur)[prop] || '';
                }
            }
        }
    };
    
    init.prepare = function(context) {
        
        // handle if a dom collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodename) {
            // is a dom collection:
            var allcontexts = array.prototype.slice.call(context),
                cindex = -1, clen = allcontexts.length;
            while (cindex<clen) { init.prepare.call(null, allcontexts[cindex]); }
            return;
        }
        
        // slowly recurses through all elements
        // so as not to lock up on the user.
        
        context = context || document.documentelement;
        
        if (!document.createelement('canvas').getcontext) { return; }
        
        var all = getallnodes(context),
            i = -1, len = all.length;
        
        while (i<len) {
            var cur = all[i];
            if (data(cur).skip) { return; }
            if (cur.nodename.tolowercase() === 'img') {
                if (cur.getattribute('src') && !isexternal(cur.src)) {
                    desatimg(cur, true);
                }
                
            } else {
                var style = getstyle(cur, 'backgroundimage');
                if (style.indexof(' > -1) {
                    var urlpatt = /\(['"]?(. ?)['"]?\)/,
                        url = style.match(urlpatt)[1];
                    if (!isexternal(url)) {
                        var temp = document.createelement('img');
                        temp.src = url;
                        desatimg(temp, true, cur);
                    }
                }
            }
        }
    };
    
    return init;
})();

这有grayscale.js的前提下,我新建了turngray_ie.js。代码如下:

window.onload=function(){
  grayscale(document.body);
}

在需要变灰的网页代码和之间引入grayscale.js和turngray_ie.js

<script type="text/javascript" src="../assets/js/grayscale.js" ></script>
<script type="text/javascript" src="../assets/js/turngray_ie.js" ></script>

验证是否有效果

省略。涉及到隐私,暂不展示。我试过,无论在手机端还是pc端,无论是android 、ios、还是windows的终端都ok,都有网站置灰的效果。

不足之处

在ie浏览器,window.onload比较消耗客户端浏览器资源,所以加载稍微迟缓。但一般看不出来。
(声明:本人非前端开发人员,仅仅是解决问题。不喜勿喷)

补充-在网站发布系统操作更方便

思路:在一对多网站发布系统中,写一个文件管理功能,可以增加css和js文件以及修改代码,并将本地目录,即发布系统所在服务器网站母版目录,同步到所有ihs服务器或者其他类型的服务器。这样就不用登录每台网站服务器,每个文件去引入css和js了。节省了工作量。具体是在每个html引入以下3行:


然后把turngray.css、grayscale.js、turngray_ie.js放到对应的目录。(相对路径根据实际项目目录来定,此处仅仅举例)
再就是将改动的文件全部同步到各个网站服务器
注:一对多是自定义说法,表示一个发布系统多个网站服务器

本文标签: