DD_belatedPNG_0.0.8a.js 12 KB

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