How to use JavaScript to implement an opaque png Image background in ie6

Source: Internet
Author: User
Tags hasownproperty

When we often use png images, the background is not transparent in ie6. The following describes how to solve this problem in js.
First, we need to use a js. The Code is as follows: Copy codeThe Code is as follows :/**
* DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML .
* Author: Drew Diller
* Email: drew.diller@gmail.com
* URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.8a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png _ bg '); // argument is a CSS selector
* DD_belatedPNG.fixPng (someNode); // argument is an HTMLDomElement
**/
/*
Please read:
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!
*/
/** Rewrite by waitingbar 2012.1.12
To solve the problem that the transparent png Image under IE6 cannot be fully displayed when it is reduced
El. vml. image. fill. type = 'tile'; changed:
El. vml. image. fill. type = 'framework ';
*/

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.doc umentElement. firstChild. insertBefore (screenStyleSheet, document.doc umentElement. 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:-pixel PX; 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 has I Pr has ost for automating this! */
PrintStyleSheet = document. createElement ('style ');
PrintStyleSheet. setAttribute ('Media ', 'print ');
Document.doc umentElement. firstChild. insertBefore (printStyleSheet, document.doc umentElement. 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 */
}
},
Handlepseudo dohover: 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. iner'
**/
Fix: function (selector ){
If (this. screenStyleSheet ){
Var selectors, I;
Selectors = selector. split (',');/* multiple selectors supported, no need for multiple CALS 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.css Text = '';
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: 'handlefalsehover ', mouseenter: 'handleupload', focus: 'handleupload', blur: 'handleupload '};
For (a in moreForAs ){
If (moreForAs. hasOwnProperty ()){
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 ('onpropertychang', 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.css Text = 'behavior: none; position: absolute; left:-pixel PX; top:-pixel PX; 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 = 'ddd ';
}
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. image. fill. type = 'framework';/* 2012.1.12 */
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.exe cCommand ("BackgroundImageCache", false, true);/* TredoSoft Multiple IE doesn't like this, so try {} it */
} Catch (r ){}
DD_belatedPNG.createVmlNameSpace ();
DD_belatedPNG.createVmlStyleSheet ();

Next let's take a look at how to use this js:
DD_belatedPNG is a PNG transparent JS plug-in perfect solution for IE6. DD_belatedPNG uses Microsoft's VML language to redraw PNG images to achieve translucent effect, it also supports the background-position and background-repeat attributes and pseudo classes. DD_belatedPNG is the best solution to the png transparency issue in many ie6 environments, and others have many negative effects.

Usage:Copy codeThe Code is as follows: <! -- [If IE 6]> <script src = "DD_belatedPNG.js"> </script> <script> DD_belatedPNG.fix('.png _ bg '); </script> <! [Endif] -->

The referenced function is DD_belatedPNG.fix (). Change * css selector .png _ bg in the brackets to your css selector name.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.