dd_belatedpng.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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)) {
  124. handler = function () {
  125. self[handlers[h]](el);
  126. };
  127. el.attachEvent('on' + h, handler);
  128. }
  129. }
  130. el.attachEvent('onpropertychange', this.readPropertyChange);
  131. },
  132. giveLayout: function (el) {
  133. el.style.zoom = 1;
  134. if (el.currentStyle.position == 'static') {
  135. el.style.position = 'relative';
  136. }
  137. },
  138. copyImageBorders: function (el) {
  139. var styles, s;
  140. styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
  141. for (s in styles) {
  142. if (styles.hasOwnProperty(s)) {
  143. el.vml.color.shape.style[s] = el.currentStyle[s];
  144. }
  145. }
  146. },
  147. vmlFill: function (el) {
  148. if (!el.currentStyle) {
  149. return;
  150. } else {
  151. var elStyle, noImg, lib, v, img, imgLoaded;
  152. elStyle = el.currentStyle;
  153. }
  154. for (v in el.vml) {
  155. if (el.vml.hasOwnProperty(v)) {
  156. el.vml[v].shape.style.zIndex = elStyle.zIndex;
  157. }
  158. }
  159. el.runtimeStyle.backgroundColor = '';
  160. el.runtimeStyle.backgroundImage = '';
  161. noImg = true;
  162. if (elStyle.backgroundImage != 'none' || el.isImg) {
  163. if (!el.isImg) {
  164. el.vmlBg = elStyle.backgroundImage;
  165. el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
  166. }
  167. else {
  168. el.vmlBg = el.src;
  169. }
  170. lib = this;
  171. if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
  172. img = document.createElement('img');
  173. lib.imgSize[el.vmlBg] = img;
  174. img.className = lib.ns + '_sizeFinder';
  175. 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! */
  176. imgLoaded = function () {
  177. this.width = this.offsetWidth; /* weird cache-busting requirement! */
  178. this.height = this.offsetHeight;
  179. lib.vmlOffsets(el);
  180. };
  181. img.attachEvent('onload', imgLoaded);
  182. img.src = el.vmlBg;
  183. img.removeAttribute('width');
  184. img.removeAttribute('height');
  185. document.body.insertBefore(img, document.body.firstChild);
  186. }
  187. el.vml.image.fill.src = el.vmlBg;
  188. noImg = false;
  189. }
  190. el.vml.image.fill.on = !noImg;
  191. el.vml.image.fill.color = 'none';
  192. el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
  193. el.runtimeStyle.backgroundImage = 'none';
  194. el.runtimeStyle.backgroundColor = 'transparent';
  195. },
  196. /* 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 */
  197. vmlOffsets: function (el) {
  198. var thisStyle, size, fudge, makeVisible, bg, bgR, dC, altC, b, c, v;
  199. thisStyle = el.currentStyle;
  200. 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};
  201. fudge = (size.L + size.bLW == 1) ? 1 : 0;
  202. /* vml shape, left, top, width, height, origin */
  203. makeVisible = function (vml, l, t, w, h, o) {
  204. vml.coordsize = w+','+h;
  205. vml.coordorigin = o+','+o;
  206. vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
  207. vml.style.width = w + 'px';
  208. vml.style.height = h + 'px';
  209. vml.style.left = l + 'px';
  210. vml.style.top = t + 'px';
  211. };
  212. 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);
  213. makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1 );
  214. bg = {'X':0, 'Y':0};
  215. if (el.isImg) {
  216. bg.X = parseInt(thisStyle.paddingLeft, 10) + 1;
  217. bg.Y = parseInt(thisStyle.paddingTop, 10) + 1;
  218. }
  219. else {
  220. for (b in bg) {
  221. if (bg.hasOwnProperty(b)) {
  222. this.figurePercentage(bg, size, b, thisStyle['backgroundPosition'+b]);
  223. }
  224. }
  225. }
  226. el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
  227. bgR = thisStyle.backgroundRepeat;
  228. dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
  229. altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
  230. if (bgR != 'repeat' || el.isImg) {
  231. 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 */
  232. if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
  233. v = bgR.split('repeat-')[1].toUpperCase();
  234. c[altC[v].b1] = 1;
  235. c[altC[v].b2] = size[altC[v].d];
  236. }
  237. if (c.B > size.H) {
  238. c.B = size.H;
  239. }
  240. el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
  241. }
  242. else {
  243. el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
  244. }
  245. },
  246. figurePercentage: function (bg, size, axis, position) {
  247. var horizontal, fraction;
  248. fraction = true;
  249. horizontal = (axis == 'X');
  250. switch(position) {
  251. case 'left':
  252. case 'top':
  253. bg[axis] = 0;
  254. break;
  255. case 'center':
  256. bg[axis] = 0.5;
  257. break;
  258. case 'right':
  259. case 'bottom':
  260. bg[axis] = 1;
  261. break;
  262. default:
  263. if (position.search('%') != -1) {
  264. bg[axis] = parseInt(position, 10) / 100;
  265. }
  266. else {
  267. fraction = false;
  268. }
  269. }
  270. bg[axis] = Math.ceil( fraction ? ( (size[horizontal?'W': 'H'] * bg[axis]) - (size[horizontal?'w': 'h'] * bg[axis]) ) : parseInt(position, 10) );
  271. if (bg[axis] % 2 === 0) {
  272. bg[axis]++;
  273. }
  274. return bg[axis];
  275. },
  276. fixPng: function (el) {
  277. el.style.behavior = 'none';
  278. var lib, els, nodeStr, v, e;
  279. if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
  280. return;
  281. }
  282. el.isImg = false;
  283. if (el.nodeName == 'IMG') {
  284. if(el.src.toLowerCase().search(/\.png$/) != -1) {
  285. el.isImg = true;
  286. el.style.visibility = 'hidden';
  287. }
  288. else {
  289. return;
  290. }
  291. }
  292. else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
  293. return;
  294. }
  295. lib = DD_belatedPNG;
  296. el.vml = {color: {}, image: {}};
  297. els = {shape: {}, fill: {}};
  298. for (v in el.vml) {
  299. if (el.vml.hasOwnProperty(v)) {
  300. for (e in els) {
  301. if (els.hasOwnProperty(e)) {
  302. nodeStr = lib.ns + ':' + e;
  303. el.vml[v][e] = document.createElement(nodeStr);
  304. }
  305. }
  306. el.vml[v].shape.stroked = false;
  307. el.vml[v].shape.appendChild(el.vml[v].fill);
  308. el.parentNode.insertBefore(el.vml[v].shape, el);
  309. }
  310. }
  311. el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
  312. el.vml.image.fill.type = 'tile'; /* Makes image show up. */
  313. el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
  314. lib.attachHandlers(el);
  315. lib.giveLayout(el);
  316. lib.giveLayout(el.offsetParent);
  317. el.vmlInitiated = true;
  318. lib.applyVML(el); /* Render! */
  319. }
  320. };
  321. try {
  322. document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
  323. } catch(r) {}
  324. DD_belatedPNG.createVmlNameSpace();
  325. DD_belatedPNG.createVmlStyleSheet();