IE6不支持PNG-24图片一直困扰很多人,但是可以通过IE的独有的滤镜来解决,解决的方案很多,比如:将滤镜写在CSS里,还可以写成单独的 Javascript文件,本来认为推荐两种做法:第一种,将所有PNG图片添加滤镜(此方法有副作用);第二种:有选择性的添加滤镜(推荐);两者都可 以将代码放在单独的JS文件里,然后引用。

第一种:

直接添加如下代码:

JSCode

  1. function correctPNG() {
  2. for (var i = 0; i < document.images.length; i++) {
  3. var img = document.images[i];
  4. var imgName = img.src.toUpperCase();
  5. if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
  6. var imgID = (img.id) ? "id='" + img.id + "' " : "";
  7. var imgClass = (img.className) ? "class='" + img.className + "' " : "";
  8. var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
  9. var imgStyle = "display:inline-block;" + img.style.cssText;
  10. if (img.align == "left") {
  11. imgStyle = "float:left;" + imgStyle;
  12. }
  13. if (img.align == "right") {
  14. imgStyle = "float:right;" + imgStyle;
  15. }
  16. if (img.parentElement.href) {
  17. imgStyle = "cursor:hand;" + imgStyle;
  18. }
  19. 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>";
  20. img.outerHTML = strNewHTML;
  21. i = i - 1;
  22. }
  23. }
  24. }
  25. function alphaBackgrounds() {
  26. var rslt = navigator.appVersion.match(/MSIE(d+.d+)/, '');
  27. var itsAllGood = (rslt !== null && Number(rslt[1]) >= 5.5);
  28. for (i = 0; i < document.all.length; i++) {
  29. var bg = document.all[i].currentStyle.backgroundImage;
  30. if (bg) {
  31. if (bg.match(/.png/i) !== null) {
  32. var mypng = bg.substring(5, bg.length - 2);
  33. document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src ='" +
  34. mypng + "',sizingMethod='crop')";
  35. document.all[i].style.backgroundImage = "url('')";
  36. }
  37. }
  38. }
  39. }
  40. if (navigator.userAgent.indexOf("MSIE 6.0") > -1) {
  41. window.attachEvent("onload", correctPNG);
  42. window.attachEvent("onload", alphaBackgrounds);
  43. }

第二种:

1)添加以下代码:

JSCode

  1. var DD_belatedPNG = {
  2. ns: 'DD_belatedPNG',
  3. imgSize: {},
  4. delay: 10,
  5. nodesFixed: 0,
  6. createVmlNameSpace: function () { /* enable VML */
  7. if (document.namespaces && !document.namespaces[this.ns]) {
  8. document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
  9. }
  10. },
  11. createVmlStyleSheet: function () { /* style VML, enable behaviors */
  12. /*
  13. Just in case lots of other developers have added
  14. lots of other stylesheets using document.createStyleSheet
  15. and hit the 31-limit mark, let's not use that method!
  16. further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
  17. */
  18. var screenStyleSheet, printStyleSheet;
  19. screenStyleSheet = document.createElement('style');
  20. screenStyleSheet.setAttribute('media', 'screen');
  21. document.documentElement.firstChild.insertBefore(screenStyleSheet, document.documentElement.firstChild.firstChild);
  22. if (screenStyleSheet.styleSheet) {
  23. screenStyleSheet = screenStyleSheet.styleSheet;
  24. screenStyleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
  25. screenStyleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
  26. 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/ */
  27. this.screenStyleSheet = screenStyleSheet;
  28.  
  29. /* Add a print-media stylesheet, for preventing VML artifacts from showing up in print (including preview). */
  30. /* Thanks to R閙i Pr関ost for automating this! */
  31. printStyleSheet = document.createElement('style');
  32. printStyleSheet.setAttribute('media', 'print');
  33. document.documentElement.firstChild.insertBefore(printStyleSheet, document.documentElement.firstChild.firstChild);
  34. printStyleSheet = printStyleSheet.styleSheet;
  35. printStyleSheet.addRule(this.ns + '\\:*', '{display: none !important;}');
  36. printStyleSheet.addRule('img.' + this.ns + '_sizeFinder', '{display: none !important;}');
  37. }
  38. },
  39. readPropertyChange: function () {
  40. var el, display, v;
  41. el = event.srcElement;
  42. if (!el.vmlInitiated) {
  43. return;
  44. }
  45. if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
  46. DD_belatedPNG.applyVML(el);
  47. }
  48. if (event.propertyName == 'style.display') {
  49. display = (el.currentStyle.display == 'none') ? 'none' : 'block';
  50. for (v in el.vml) {
  51. if (el.vml.hasOwnProperty(v)) {
  52. el.vml[v].shape.style.display = display;
  53. }
  54. }
  55. }
  56. if (event.propertyName.search('filter') != -1) {
  57. DD_belatedPNG.vmlOpacity(el);
  58. }
  59. },
  60. vmlOpacity: function (el) {
  61. if (el.currentStyle.filter.search('lpha') != -1) {
  62. var trans = el.currentStyle.filter;
  63. trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
  64. el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
  65. el.vml.image.fill.opacity = trans; /* complete guesswork */
  66. }
  67. },
  68. handlePseudoHover: function (el) {
  69. setTimeout(function () { /* wouldn't work as intended without setTimeout */
  70. DD_belatedPNG.applyVML(el);
  71. }, 1);
  72. },
  73. /**
  74. * This is the method to use in a document.
  75. * @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
  76. **/
  77. fix: function (selector) {
  78. if (this.screenStyleSheet) {
  79. var selectors, i;
  80. selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
  81. for (i=0; i<selectors.length; i++) {
  82. this.screenStyleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
  83. }
  84. }
  85. },
  86. applyVML: function (el) {
  87. el.runtimeStyle.cssText = '';
  88. this.vmlFill(el);
  89. this.vmlOffsets(el);
  90. this.vmlOpacity(el);
  91. if (el.isImg) {
  92. this.copyImageBorders(el);
  93. }
  94. },
  95. attachHandlers: function (el) {
  96. var self, handlers, handler, moreForAs, a, h;
  97. self = this;
  98. handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
  99. if (el.nodeName == 'A') {
  100. moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
  101. for (a in moreForAs) {
  102. if (moreForAs.hasOwnProperty(a)) {
  103. handlers[a] = moreForAs[a];
  104. }
  105. }
  106. }
  107. for (h in handlers) {
  108. if (handlers.hasOwnProperty(h)) {
  109. handler = function () {
  110. self[handlers[h]](el);
  111. };
  112. el.attachEvent('on' + h, handler);
  113. }
  114. }
  115. el.attachEvent('onpropertychange', this.readPropertyChange);
  116. },
  117. giveLayout: function (el) {
  118. el.style.zoom = 1;
  119. if (el.currentStyle.position == 'static') {
  120. el.style.position = 'relative';
  121. }
  122. },
  123. copyImageBorders: function (el) {
  124. var styles, s;
  125. styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
  126. for (s in styles) {
  127. if (styles.hasOwnProperty(s)) {
  128. el.vml.color.shape.style[s] = el.currentStyle[s];
  129. }
  130. }
  131. },
  132. vmlFill: function (el) {
  133. if (!el.currentStyle) {
  134. return;
  135. } else {
  136. var elStyle, noImg, lib, v, img, imgLoaded;
  137. elStyle = el.currentStyle;
  138. }
  139. for (v in el.vml) {
  140. if (el.vml.hasOwnProperty(v)) {
  141. el.vml[v].shape.style.zIndex = elStyle.zIndex;
  142. }
  143. }
  144. el.runtimeStyle.backgroundColor = '';
  145. el.runtimeStyle.backgroundImage = '';
  146. noImg = true;
  147. if (elStyle.backgroundImage != 'none' || el.isImg) {
  148. if (!el.isImg) {
  149. el.vmlBg = elStyle.backgroundImage;
  150. el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
  151. }
  152. else {
  153. el.vmlBg = el.src;
  154. }
  155. lib = this;
  156. if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
  157. img = document.createElement('img');
  158. lib.imgSize[el.vmlBg] = img;
  159. img.className = lib.ns + '_sizeFinder';
  160. 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! */
  161. imgLoaded = function () {
  162. this.width = this.offsetWidth; /* weird cache-busting requirement! */
  163. this.height = this.offsetHeight;
  164. lib.vmlOffsets(el);
  165. };
  166. img.attachEvent('onload', imgLoaded);
  167. img.src = el.vmlBg;
  168. img.removeAttribute('width');
  169. img.removeAttribute('height');
  170. document.body.insertBefore(img, document.body.firstChild);
  171. }
  172. el.vml.image.fill.src = el.vmlBg;
  173. noImg = false;
  174. }
  175. el.vml.image.fill.on = !noImg;
  176. el.vml.image.fill.color = 'none';
  177. el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
  178. el.runtimeStyle.backgroundImage = 'none';
  179. el.runtimeStyle.backgroundColor = 'transparent';
  180. },
  181. /* 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 */
  182. vmlOffsets: function (el) {
  183. var thisStyle, size, fudge, makeVisible, bg, bgR, dC, altC, b, c, v;
  184. thisStyle = el.currentStyle;
  185. 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};
  186. fudge = (size.L + size.bLW == 1) ? 1 : 0;
  187. /* vml shape, left, top, width, height, origin */
  188. makeVisible = function (vml, l, t, w, h, o) {
  189. vml.coordsize = w+','+h;
  190. vml.coordorigin = o+','+o;
  191. vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
  192. vml.style.width = w + 'px';
  193. vml.style.height = h + 'px';
  194. vml.style.left = l + 'px';
  195. vml.style.top = t + 'px';
  196. };
  197. 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);
  198. makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1 );
  199. bg = {'X':0, 'Y':0};
  200. if (el.isImg) {
  201. bg.X = parseInt(thisStyle.paddingLeft, 10) + 1;
  202. bg.Y = parseInt(thisStyle.paddingTop, 10) + 1;
  203. }
  204. else {
  205. for (b in bg) {
  206. if (bg.hasOwnProperty(b)) {
  207. this.figurePercentage(bg, size, b, thisStyle['backgroundPosition'+b]);
  208. }
  209. }
  210. }
  211. el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
  212. bgR = thisStyle.backgroundRepeat;
  213. dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
  214. altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
  215. if (bgR != 'repeat' || el.isImg) {
  216. 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 */
  217. if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
  218. v = bgR.split('repeat-')[1].toUpperCase();
  219. c[altC[v].b1] = 1;
  220. c[altC[v].b2] = size[altC[v].d];
  221. }
  222. if (c.B > size.H) {
  223. c.B = size.H;
  224. }
  225. el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
  226. }
  227. else {
  228. el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
  229. }
  230. },
  231. figurePercentage: function (bg, size, axis, position) {
  232. var horizontal, fraction;
  233. fraction = true;
  234. horizontal = (axis == 'X');
  235. switch(position) {
  236. case 'left':
  237. case 'top':
  238. bg[axis] = 0;
  239. break;
  240. case 'center':
  241. bg[axis] = 0.5;
  242. break;
  243. case 'right':
  244. case 'bottom':
  245. bg[axis] = 1;
  246. break;
  247. default:
  248. if (position.search('%') != -1) {
  249. bg[axis] = parseInt(position, 10) / 100;
  250. }
  251. else {
  252. fraction = false;
  253. }
  254. }
  255. bg[axis] = Math.ceil( fraction ? ( (size[horizontal?'W': 'H'] * bg[axis]) - (size[horizontal?'w': 'h'] * bg[axis]) ) : parseInt(position, 10) );
  256. if (bg[axis] % 2 === 0) {
  257. bg[axis]++;
  258. }
  259. return bg[axis];
  260. },
  261. fixPng: function (el) {
  262. el.style.behavior = 'none';
  263. var lib, els, nodeStr, v, e;
  264. if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
  265. return;
  266. }
  267. el.isImg = false;
  268. if (el.nodeName == 'IMG') {
  269. if(el.src.toLowerCase().search(/\.png$/) != -1) {
  270. el.isImg = true;
  271. el.style.visibility = 'hidden';
  272. }
  273. else {
  274. return;
  275. }
  276. }
  277. else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
  278. return;
  279. }
  280. lib = DD_belatedPNG;
  281. el.vml = {color: {}, image: {}};
  282. els = {shape: {}, fill: {}};
  283. for (v in el.vml) {
  284. if (el.vml.hasOwnProperty(v)) {
  285. for (e in els) {
  286. if (els.hasOwnProperty(e)) {
  287. nodeStr = lib.ns + ':' + e;
  288. el.vml[v][e] = document.createElement(nodeStr);
  289. }
  290. }
  291. el.vml[v].shape.stroked = false;
  292. el.vml[v].shape.appendChild(el.vml[v].fill);
  293. el.parentNode.insertBefore(el.vml[v].shape, el);
  294. }
  295. }
  296. el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
  297. el.vml.image.fill.type = 'tile'; /* Makes image show up. */
  298. el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
  299. lib.attachHandlers(el);
  300. lib.giveLayout(el);
  301. lib.giveLayout(el.offsetParent);
  302. el.vmlInitiated = true;
  303. lib.applyVML(el); /* Render! */
  304. }
  305. };
  306. try {
  307. document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
  308. } catch(r) {}
  309. DD_belatedPNG.createVmlNameSpace();
  310. DD_belatedPNG.createVmlStyleSheet();

2)第二步在调用:

  1. 1 <!--[if IE 6]>
  2. 2 <script src="js/DD_belatedPNG.js" mce_src="DD_belatedPNG.js"></script>
  3. 3 <script type="text/javascript">
  4. 4 DD_belatedPNG.fix('.class');//这里是CSS选择,多个就有分号“,”隔开;
  5. 5 如:DD_belatedPNG.fix('.class1,.class2,.class3')
  6. 6 </script>
  7. 7 <![endif]-->

第二种方法使用得比较多,可以根据需要选择滤镜,不会影响其它图片,副作用小。

虽然可以使用滤镜来解决透明的问题,但是这也是有条件的,所使用的图片不能 background-position: 与background-repeat,所以不能从根本解决问题,不过基本可以满足大部分需求了。

IE6透明PNG解决方案的更多相关文章

  1. 【转载】IE6 PNG透明终极解决方案(打造W3Cfuns-IE6PNG最强帖)

    原文地址:http://www.w3cfuns.com/thread-297-1-1.html 本文版权归W3Cfuns.com所有,转载需在文章页面明显位置以链接的方式给出原文链接,否则W3Cfun ...

  2. IE6下Png透明最佳解决方案(推荐) Unit PNG Fix

    引自:http://www.yeeyan.org/articles/view/98510/67784 网络上解决IE6下Png透明解决方案有很多,例如 IE PNG Fix from TwinHeli ...

  3. IE6 PNG图片不透明的解决方案-tinypng

    https://tinypng.com/ 把图片上传上去,就能处理这个问题啦. 纠正一下 再也不用把png图片一个个拖到TinyPNG进行在线压缩(和熊猫哥哥说再见了):再不用把JPG/JPEG图片拖 ...

  4. IE6 BUG及解决方案

    1.IE6中奇数宽高的BUG 一个外部的相对定位div,内部一个绝对定位的div(right:0) 可是在IE6下查看,却变成了right:1px的效果了: 解决方案就是将外部相对定位的div宽度改成 ...

  5. 前端点击png透明部分解决方案

    看效果:点击空白区域红色1.点击实体区域红色2.分别得到颜色数据(包括透明度数据),控制台蓝色1.2.根据颜色数据即可解决png透明部分的点击问题. 让图片不能点击,分两种 1. 整张图片不能点击.这 ...

  6. 父容器利用opacity设置透明后,子元素跟着变透明的解决方案

    背景半透明,子元素不透明的效果经常需要用到.通常对父容器使用opacity属性时,子元素也跟着变透明,所以不妨设置父容器的 background-color:rgba(r,g,b,x); 其中x取值从 ...

  7. IE6下CSS常见兼容性问题及解决方案

    1. 在IE6元素浮动,如果宽度需要内容撑开,就给里面的块元素加浮动. 2. IE6下最小高度问题:在IE6下元素高度小于19px的时候,会被当作19px处理.解决方案:给元素加 overflow:h ...

  8. ie6背景透明的设置方法 ie6背景颜色透明和png图像透明解决方法

    IE6浏览器,让我们又爱又恨.爱它的是,可以让我们写的代码的时候,可以更标准,恨的是,它有太多无厘头的IE6常见bug(详情点击),让我们焦头烂额.现在现在用百度浏览器调查,国内占有率不到6%了,但是 ...

  9. IE6 的兼容相关问题

    因为在实习公司要求兼容IE6+,所以将IE6相关的样式兼容问题列出,及解决方案. 1.让页面变丑的透明背景图片问题: HTML都为以下代码: <div class="img-png&q ...

随机推荐

  1. TP中CURD操作

    CURD操作 CURD操作也就是模型操作数据表的基本操作.C(Create).U(Update).R(Read).D(Delete)操作就是增删改查操作. 6.1.增加操作 回想一下在mysql中增加 ...

  2. 九度-题目1026:又一版 A+B

    http://ac.jobdu.com/problem.php?pid=1026 题目描述: 输入两个不超过整型定义的非负10进制整数A和B(<=231-1),输出A+B的m (1 < m ...

  3. utuntu下安装eclipse+jdk

    安装jdk: 1.下载一个可以用的jdk压缩包.下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads- ...

  4. BZOJ 1189 紧急疏散(二分+最大流)

    求出所有人撤离的最短时间.由于每扇门只能通过一次,所以不能简单用bfs来搞. 显然答案是有单调性的,考虑二分,问题变成了判断时间x所有人能不能撤离. 考虑最大流.对于每扇门,每个时间通过的人数最多为1 ...

  5. 我的bootstrap学习

    前端开发框架bootstrap Bootstrap 安装     <link ref="stylesheet" href="bs/css/bootstrap.css ...

  6. BZOJ3747 POI2015Kinoman(线段树)

    考虑固定左端点,求出该情况下能获得的最大值.于是每次可以在某数第一次出现的位置加上其价值,第二次出现的位置减掉其价值,查询前缀最大值就可以了.每次移动左端点在线段树上更新即可. #include< ...

  7. 51nod 1526 分配笔名(字典树+贪心)

    题意: 班里有n个同学.老师为他们选了n个笔名.现在要把这些笔名分配给每一个同学,每一个同学分配到一个笔名,每一个笔名必须分配给某个同学.现在定义笔名和真名之间的相关度是他们之间的最长公共前缀.设笔名 ...

  8. Visual Format Language(VFL)视图约束

    约束(Constraint)在IOS编程中非常重要,这关乎到用户的直接体验问题. IOS中视图约束有几种方式,常见的是在IB中通过Pin的方式手动添加约束,菜单Editor->Pin->. ...

  9. Unity3D手游开发日记(4) - 适合移动平台的热浪扭曲

    热浪扭曲效果的实现,分两部分,一是抓图,二是扭曲扰动.其中难点在于抓图的处理,网上的解决方案有两种,在移动平台都有很多问题,只好自己实现了一种新的方案,效果还不错. 网上方案1. 用GrabPass抓 ...

  10. Unity3D实现3D立体游戏原理及过程

    Unity3D实现3D立体游戏原理及过程 183 0 0     下面的教程是我今天整理的资料,教大家一步步完成自己的3D立体游戏,并向大家介绍一些3D成像的原理.     理论上,每个普通的非立体3 ...