本渐进处理只适用于图片。如果要兼容文字,需要使用元素,非这里的元素,具体参见SVG教程。 可以IE10,IE11等不支持CSS 灰度滤镜的SVG兼容。高斯模糊等滤镜效果,也是类似的原理。 其中,image参数,可以是DOM对象,也可以是DOMList,也可以是jQuery包装器集合。表示,需要灰度的图片和图片们。
- var exports = {
- /*
- * image grayscale for IE10-IE12
- * @param { object|array } [image] DOM, DOMList, or jQuery wrapper
- **/
- grayscale: function(image) {
- var self = this;
-
- // 检测是否支持标准滤镜
- var isUnsupport = (function() {
- if (document.msHidden != 'undefined') {
- var div = document.createElement('div'), value = 'grayscale(100%)';
- div.style.filter = value;
-
- return window.getComputedStyle(div).filter !== value;
- }
- })();
-
-
- // only IE10+ and not support filter
- if (image && isUnsupport == true) {
- if (image.length > 0) {
- if (image.each) {
- image.each(function() {
- self.grayscale(this);
- });
- } else if (image.forEach) {
- image.forEach(function(img) {
- self.grayscale(img);
- });
- }
- } else if (/img/i.test(image.tagName)) {
- // 载入SVG滤镜
- if (!document.grayscale) {
- document.body.insertAdjacentHTML('afterBegin', '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" class="dn">\
- <filter id="grayscale">\
- <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/>\
- </filter>\
- </svg>');
- document.grayscale = true;
- }
-
- // 图片变SVG
- var cl = image.className, src = image.src;
- // 尺寸
- var width = image.clientWidth, height = image.clientHeight;
-
- if (!image.grayscale) {
- image.insertAdjacentHTML('beforeBegin', '<svg class="'+ cl +'"><image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="'+ src +'" x="0" y="0" width="'+ width +'" height="'+ height +'" filter="url(\'#grayscale\')"></image></svg>');
- }
- }
-
- return this;
- }
- }
- }