IE6透明PNG解决方案
IE6不支持PNG-24图片一直困扰很多人,但是可以通过IE的独有的滤镜来解决,解决的方案很多,比如:将滤镜写在CSS里,还可以写成单独的 Javascript文件,本来认为推荐两种做法:第一种,将所有PNG图片添加滤镜(此方法有副作用);第二种:有选择性的添加滤镜(推荐);两者都可 以将代码放在单独的JS文件里,然后引用。
第一种:
直接添加如下代码:
- function correctPNG() {
- for (var i = 0; i < document.images.length; i++) {
- var img = document.images[i];
- var imgName = img.src.toUpperCase();
- if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
- var imgID = (img.id) ? "id='" + img.id + "' " : "";
- var imgClass = (img.className) ? "class='" + img.className + "' " : "";
- var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
- var imgStyle = "display:inline-block;" + img.style.cssText;
- if (img.align == "left") {
- imgStyle = "float:left;" + imgStyle;
- }
- if (img.align == "right") {
- imgStyle = "float:right;" + imgStyle;
- }
- if (img.parentElement.href) {
- imgStyle = "cursor:hand;" + imgStyle;
- }
- var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
- img.outerHTML = strNewHTML;
- i = i - 1;
- }
- }
- }
- function alphaBackgrounds() {
- var rslt = navigator.appVersion.match(/MSIE(d+.d+)/, '');
- var itsAllGood = (rslt !== null && Number(rslt[1]) >= 5.5);
- for (i = 0; i < document.all.length; i++) {
- var bg = document.all[i].currentStyle.backgroundImage;
- if (bg) {
- if (bg.match(/.png/i) !== null) {
- var mypng = bg.substring(5, bg.length - 2);
- document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src ='" +
- mypng + "',sizingMethod='crop')";
- document.all[i].style.backgroundImage = "url('')";
- }
- }
- }
- }
- if (navigator.userAgent.indexOf("MSIE 6.0") > -1) {
- window.attachEvent("onload", correctPNG);
- window.attachEvent("onload", alphaBackgrounds);
- }
第二种:
1)添加以下代码:
- var DD_belatedPNG = {
- ns: 'DD_belatedPNG',
- imgSize: {},
- delay: 10,
- nodesFixed: 0,
- createVmlNameSpace: function () { /* enable VML */
- if (document.namespaces && !document.namespaces[this.ns]) {
- document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
- }
- },
- createVmlStyleSheet: function () { /* style VML, enable behaviors */
- /*
- Just in case lots of other developers have added
- lots of other stylesheets using document.createStyleSheet
- and hit the 31-limit mark, let's not use that method!
- further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
- */
- var screenStyleSheet, printStyleSheet;
- screenStyleSheet = document.createElement('style');
- screenStyleSheet.setAttribute('media', 'screen');
- document.documentElement.firstChild.insertBefore(screenStyleSheet, document.documentElement.firstChild.firstChild);
- if (screenStyleSheet.styleSheet) {
- screenStyleSheet = screenStyleSheet.styleSheet;
- screenStyleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
- screenStyleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
- screenStyleSheet.addRule('img.' + this.ns + '_sizeFinder', 'behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;'); /* large negative top value for avoiding vertical scrollbars for large images, suggested by James O'Brien, http://www.thanatopsic.org/hendrik/ */
- this.screenStyleSheet = screenStyleSheet;
- /* Add a print-media stylesheet, for preventing VML artifacts from showing up in print (including preview). */
- /* Thanks to R閙i Pr関ost for automating this! */
- printStyleSheet = document.createElement('style');
- printStyleSheet.setAttribute('media', 'print');
- document.documentElement.firstChild.insertBefore(printStyleSheet, document.documentElement.firstChild.firstChild);
- printStyleSheet = printStyleSheet.styleSheet;
- printStyleSheet.addRule(this.ns + '\\:*', '{display: none !important;}');
- printStyleSheet.addRule('img.' + this.ns + '_sizeFinder', '{display: none !important;}');
- }
- },
- readPropertyChange: function () {
- var el, display, v;
- el = event.srcElement;
- if (!el.vmlInitiated) {
- return;
- }
- if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
- DD_belatedPNG.applyVML(el);
- }
- if (event.propertyName == 'style.display') {
- display = (el.currentStyle.display == 'none') ? 'none' : 'block';
- for (v in el.vml) {
- if (el.vml.hasOwnProperty(v)) {
- el.vml[v].shape.style.display = display;
- }
- }
- }
- if (event.propertyName.search('filter') != -1) {
- DD_belatedPNG.vmlOpacity(el);
- }
- },
- vmlOpacity: function (el) {
- if (el.currentStyle.filter.search('lpha') != -1) {
- var trans = el.currentStyle.filter;
- trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
- el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
- el.vml.image.fill.opacity = trans; /* complete guesswork */
- }
- },
- handlePseudoHover: function (el) {
- setTimeout(function () { /* wouldn't work as intended without setTimeout */
- DD_belatedPNG.applyVML(el);
- }, 1);
- },
- /**
- * This is the method to use in a document.
- * @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
- **/
- fix: function (selector) {
- if (this.screenStyleSheet) {
- var selectors, i;
- selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
- for (i=0; i<selectors.length; i++) {
- this.screenStyleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
- }
- }
- },
- applyVML: function (el) {
- el.runtimeStyle.cssText = '';
- this.vmlFill(el);
- this.vmlOffsets(el);
- this.vmlOpacity(el);
- if (el.isImg) {
- this.copyImageBorders(el);
- }
- },
- attachHandlers: function (el) {
- var self, handlers, handler, moreForAs, a, h;
- self = this;
- handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
- if (el.nodeName == 'A') {
- moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
- for (a in moreForAs) {
- if (moreForAs.hasOwnProperty(a)) {
- handlers[a] = moreForAs[a];
- }
- }
- }
- for (h in handlers) {
- if (handlers.hasOwnProperty(h)) {
- handler = function () {
- self[handlers[h]](el);
- };
- el.attachEvent('on' + h, handler);
- }
- }
- el.attachEvent('onpropertychange', this.readPropertyChange);
- },
- giveLayout: function (el) {
- el.style.zoom = 1;
- if (el.currentStyle.position == 'static') {
- el.style.position = 'relative';
- }
- },
- copyImageBorders: function (el) {
- var styles, s;
- styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
- for (s in styles) {
- if (styles.hasOwnProperty(s)) {
- el.vml.color.shape.style[s] = el.currentStyle[s];
- }
- }
- },
- vmlFill: function (el) {
- if (!el.currentStyle) {
- return;
- } else {
- var elStyle, noImg, lib, v, img, imgLoaded;
- elStyle = el.currentStyle;
- }
- for (v in el.vml) {
- if (el.vml.hasOwnProperty(v)) {
- el.vml[v].shape.style.zIndex = elStyle.zIndex;
- }
- }
- el.runtimeStyle.backgroundColor = '';
- el.runtimeStyle.backgroundImage = '';
- noImg = true;
- if (elStyle.backgroundImage != 'none' || el.isImg) {
- if (!el.isImg) {
- el.vmlBg = elStyle.backgroundImage;
- el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
- }
- else {
- el.vmlBg = el.src;
- }
- lib = this;
- if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
- img = document.createElement('img');
- lib.imgSize[el.vmlBg] = img;
- img.className = lib.ns + '_sizeFinder';
- img.runtimeStyle.cssText = 'behavior:none; position:absolute; left:-10000px; top:-10000px; border:none; margin:0; padding:0;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
- imgLoaded = function () {
- this.width = this.offsetWidth; /* weird cache-busting requirement! */
- this.height = this.offsetHeight;
- lib.vmlOffsets(el);
- };
- img.attachEvent('onload', imgLoaded);
- img.src = el.vmlBg;
- img.removeAttribute('width');
- img.removeAttribute('height');
- document.body.insertBefore(img, document.body.firstChild);
- }
- el.vml.image.fill.src = el.vmlBg;
- noImg = false;
- }
- el.vml.image.fill.on = !noImg;
- el.vml.image.fill.color = 'none';
- el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
- el.runtimeStyle.backgroundImage = 'none';
- el.runtimeStyle.backgroundColor = 'transparent';
- },
- /* IE can't figure out what do when the offsetLeft and the clientLeft add up to 1, and the VML ends up getting fuzzy... so we have to push/enlarge things by 1 pixel and then clip off the excess */
- vmlOffsets: function (el) {
- var thisStyle, size, fudge, makeVisible, bg, bgR, dC, altC, b, c, v;
- thisStyle = el.currentStyle;
- size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':this.imgSize[el.vmlBg].width, 'h':this.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
- fudge = (size.L + size.bLW == 1) ? 1 : 0;
- /* vml shape, left, top, width, height, origin */
- makeVisible = function (vml, l, t, w, h, o) {
- vml.coordsize = w+','+h;
- vml.coordorigin = o+','+o;
- vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
- vml.style.width = w + 'px';
- vml.style.height = h + 'px';
- vml.style.left = l + 'px';
- vml.style.top = t + 'px';
- };
- makeVisible(el.vml.color.shape, (size.L + (el.isImg ? 0 : size.bLW)), (size.T + (el.isImg ? 0 : size.bTW)), (size.W-1), (size.H-1), 0);
- makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1 );
- bg = {'X':0, 'Y':0};
- if (el.isImg) {
- bg.X = parseInt(thisStyle.paddingLeft, 10) + 1;
- bg.Y = parseInt(thisStyle.paddingTop, 10) + 1;
- }
- else {
- for (b in bg) {
- if (bg.hasOwnProperty(b)) {
- this.figurePercentage(bg, size, b, thisStyle['backgroundPosition'+b]);
- }
- }
- }
- el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
- bgR = thisStyle.backgroundRepeat;
- dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
- altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
- if (bgR != 'repeat' || el.isImg) {
- c = {'T':(bg.Y), 'R':(bg.X+size.w), 'B':(bg.Y+size.h), 'L':(bg.X)}; /* these are defaults for no-repeat - clips down to the image location */
- if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
- v = bgR.split('repeat-')[1].toUpperCase();
- c[altC[v].b1] = 1;
- c[altC[v].b2] = size[altC[v].d];
- }
- if (c.B > size.H) {
- c.B = size.H;
- }
- el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
- }
- else {
- el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
- }
- },
- figurePercentage: function (bg, size, axis, position) {
- var horizontal, fraction;
- fraction = true;
- horizontal = (axis == 'X');
- switch(position) {
- case 'left':
- case 'top':
- bg[axis] = 0;
- break;
- case 'center':
- bg[axis] = 0.5;
- break;
- case 'right':
- case 'bottom':
- bg[axis] = 1;
- break;
- default:
- if (position.search('%') != -1) {
- bg[axis] = parseInt(position, 10) / 100;
- }
- else {
- fraction = false;
- }
- }
- bg[axis] = Math.ceil( fraction ? ( (size[horizontal?'W': 'H'] * bg[axis]) - (size[horizontal?'w': 'h'] * bg[axis]) ) : parseInt(position, 10) );
- if (bg[axis] % 2 === 0) {
- bg[axis]++;
- }
- return bg[axis];
- },
- fixPng: function (el) {
- el.style.behavior = 'none';
- var lib, els, nodeStr, v, e;
- if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
- return;
- }
- el.isImg = false;
- if (el.nodeName == 'IMG') {
- if(el.src.toLowerCase().search(/\.png$/) != -1) {
- el.isImg = true;
- el.style.visibility = 'hidden';
- }
- else {
- return;
- }
- }
- else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
- return;
- }
- lib = DD_belatedPNG;
- el.vml = {color: {}, image: {}};
- els = {shape: {}, fill: {}};
- for (v in el.vml) {
- if (el.vml.hasOwnProperty(v)) {
- for (e in els) {
- if (els.hasOwnProperty(e)) {
- nodeStr = lib.ns + ':' + e;
- el.vml[v][e] = document.createElement(nodeStr);
- }
- }
- el.vml[v].shape.stroked = false;
- el.vml[v].shape.appendChild(el.vml[v].fill);
- el.parentNode.insertBefore(el.vml[v].shape, el);
- }
- }
- el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
- el.vml.image.fill.type = 'tile'; /* Makes image show up. */
- el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
- lib.attachHandlers(el);
- lib.giveLayout(el);
- lib.giveLayout(el.offsetParent);
- el.vmlInitiated = true;
- lib.applyVML(el); /* Render! */
- }
- };
- try {
- document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
- } catch(r) {}
- DD_belatedPNG.createVmlNameSpace();
- DD_belatedPNG.createVmlStyleSheet();
2)第二步在调用:
- 1 <!--[if IE 6]>
- 2 <script src="js/DD_belatedPNG.js" mce_src="DD_belatedPNG.js"></script>
- 3 <script type="text/javascript">
- 4 DD_belatedPNG.fix('.class');//这里是CSS选择,多个就有分号“,”隔开;
- 5 如:DD_belatedPNG.fix('.class1,.class2,.class3')
- 6 </script>
- 7 <![endif]-->
第二种方法使用得比较多,可以根据需要选择滤镜,不会影响其它图片,副作用小。
虽然可以使用滤镜来解决透明的问题,但是这也是有条件的,所使用的图片不能 background-position: 与background-repeat,所以不能从根本解决问题,不过基本可以满足大部分需求了。
IE6透明PNG解决方案的更多相关文章
- 【转载】IE6 PNG透明终极解决方案(打造W3Cfuns-IE6PNG最强帖)
原文地址:http://www.w3cfuns.com/thread-297-1-1.html 本文版权归W3Cfuns.com所有,转载需在文章页面明显位置以链接的方式给出原文链接,否则W3Cfun ...
- IE6下Png透明最佳解决方案(推荐) Unit PNG Fix
引自:http://www.yeeyan.org/articles/view/98510/67784 网络上解决IE6下Png透明解决方案有很多,例如 IE PNG Fix from TwinHeli ...
- IE6 PNG图片不透明的解决方案-tinypng
https://tinypng.com/ 把图片上传上去,就能处理这个问题啦. 纠正一下 再也不用把png图片一个个拖到TinyPNG进行在线压缩(和熊猫哥哥说再见了):再不用把JPG/JPEG图片拖 ...
- IE6 BUG及解决方案
1.IE6中奇数宽高的BUG 一个外部的相对定位div,内部一个绝对定位的div(right:0) 可是在IE6下查看,却变成了right:1px的效果了: 解决方案就是将外部相对定位的div宽度改成 ...
- 前端点击png透明部分解决方案
看效果:点击空白区域红色1.点击实体区域红色2.分别得到颜色数据(包括透明度数据),控制台蓝色1.2.根据颜色数据即可解决png透明部分的点击问题. 让图片不能点击,分两种 1. 整张图片不能点击.这 ...
- 父容器利用opacity设置透明后,子元素跟着变透明的解决方案
背景半透明,子元素不透明的效果经常需要用到.通常对父容器使用opacity属性时,子元素也跟着变透明,所以不妨设置父容器的 background-color:rgba(r,g,b,x); 其中x取值从 ...
- IE6下CSS常见兼容性问题及解决方案
1. 在IE6元素浮动,如果宽度需要内容撑开,就给里面的块元素加浮动. 2. IE6下最小高度问题:在IE6下元素高度小于19px的时候,会被当作19px处理.解决方案:给元素加 overflow:h ...
- ie6背景透明的设置方法 ie6背景颜色透明和png图像透明解决方法
IE6浏览器,让我们又爱又恨.爱它的是,可以让我们写的代码的时候,可以更标准,恨的是,它有太多无厘头的IE6常见bug(详情点击),让我们焦头烂额.现在现在用百度浏览器调查,国内占有率不到6%了,但是 ...
- IE6 的兼容相关问题
因为在实习公司要求兼容IE6+,所以将IE6相关的样式兼容问题列出,及解决方案. 1.让页面变丑的透明背景图片问题: HTML都为以下代码: <div class="img-png&q ...
随机推荐
- TP中CURD操作
CURD操作 CURD操作也就是模型操作数据表的基本操作.C(Create).U(Update).R(Read).D(Delete)操作就是增删改查操作. 6.1.增加操作 回想一下在mysql中增加 ...
- 九度-题目1026:又一版 A+B
http://ac.jobdu.com/problem.php?pid=1026 题目描述: 输入两个不超过整型定义的非负10进制整数A和B(<=231-1),输出A+B的m (1 < m ...
- utuntu下安装eclipse+jdk
安装jdk: 1.下载一个可以用的jdk压缩包.下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads- ...
- BZOJ 1189 紧急疏散(二分+最大流)
求出所有人撤离的最短时间.由于每扇门只能通过一次,所以不能简单用bfs来搞. 显然答案是有单调性的,考虑二分,问题变成了判断时间x所有人能不能撤离. 考虑最大流.对于每扇门,每个时间通过的人数最多为1 ...
- 我的bootstrap学习
前端开发框架bootstrap Bootstrap 安装 <link ref="stylesheet" href="bs/css/bootstrap.css ...
- BZOJ3747 POI2015Kinoman(线段树)
考虑固定左端点,求出该情况下能获得的最大值.于是每次可以在某数第一次出现的位置加上其价值,第二次出现的位置减掉其价值,查询前缀最大值就可以了.每次移动左端点在线段树上更新即可. #include< ...
- 51nod 1526 分配笔名(字典树+贪心)
题意: 班里有n个同学.老师为他们选了n个笔名.现在要把这些笔名分配给每一个同学,每一个同学分配到一个笔名,每一个笔名必须分配给某个同学.现在定义笔名和真名之间的相关度是他们之间的最长公共前缀.设笔名 ...
- Visual Format Language(VFL)视图约束
约束(Constraint)在IOS编程中非常重要,这关乎到用户的直接体验问题. IOS中视图约束有几种方式,常见的是在IB中通过Pin的方式手动添加约束,菜单Editor->Pin->. ...
- Unity3D手游开发日记(4) - 适合移动平台的热浪扭曲
热浪扭曲效果的实现,分两部分,一是抓图,二是扭曲扰动.其中难点在于抓图的处理,网上的解决方案有两种,在移动平台都有很多问题,只好自己实现了一种新的方案,效果还不错. 网上方案1. 用GrabPass抓 ...
- Unity3D实现3D立体游戏原理及过程
Unity3D实现3D立体游戏原理及过程 183 0 0 下面的教程是我今天整理的资料,教大家一步步完成自己的3D立体游戏,并向大家介绍一些3D成像的原理. 理论上,每个普通的非立体3 ...