PNGHandler-use JavaScript to make PNG images transparent under IE (including background images)

Source: Internet
Author: User

PNG. JS code:
// PNGHandler: Object-Oriented Javascript-based PNG wrapper
//--------------------------------------------------------
// Version 1.1.20031218
// Code by Scott Schiller-www.schillmania.com
//--------------------------------------------------------
// Description:
// Provides gracefully-degrading PNG functionality where
// PNG is supported natively or via filters (Damn you, IE !)
// Shocould work with PNGs as images and DIV background images.

Function PNGHandler (){
Var self = this;

This. na = navigator. appName. toLowerCase ();
This. nv = navigator. appVersion. toLowerCase ();
This. isIE = this. na. indexOf ('Internet explorer ') + 1? 1:0;
This. isWin = this. nv. indexOf ('windows') + 1? 1:0;
This. ver = this. isIE? ParseFloat (this. nv. split ('msie ') [1]): parseFloat (this. nv );
This. isMac = this. nv. indexOf ('mac') + 1? 1:0;
This. isOpera = (navigator. userAgent. toLowerCase (). indexOf ('Opera ') + 1 | navigator. userAgent. toLowerCase (). indexOf ('Opera/') + 1 );
If (this. isOpera) this. isIE = false; // Opera filter catch (which is sneaky, pretending to be IE by default)

This. transform = null;

This. getElementsByClassName = function (className, oParent ){
Doc = (oParent | document );
Matches = [];
Nodes = doc. all | doc. getElementsByTagName ('*');
For (I = 0; I <nodes. length; I ++ ){
If (nodes [I]. className = className | nodes [I]. className. indexOf (className) + 1 | nodes [I]. className. indexOf (className + '') + 1 | nodes [I]. className. indexOf (''+ className) + 1 ){
Matches [matches. length] = nodes [I];
}
}
Return matches; // kids, don't play with fire .;)
}

This. filterMethod = function (oOld ){
// IE 5.5 + proprietary filter garbage (boo !)
// Create new element based on old one. Doesn't seem to render properly otherwise (due to filter ?)
// Use proprietary "currentStyle" object, so rules inherited via CSS are picked up.

Var o = document. createElement ('div '); // oOld. nodeName
Var filterID = 'dximagetransform. Microsoft. AlphaImageLoader ';
// O. style. width = oOld. currentStyle. width;
// O. style. height = oOld. currentStyle. height;

If (oOld. nodeName = 'div '){
Var B = oOld. currentStyle. backgroundImage. toString (); // parse out background image URL
OOld. style. backgroundImage = 'none ';
// Parse out background image URL from currentStyle object.
Var i1 = B. indexOf ('url ("') + 5;
Var newSrc = B .substr(i1, B .length-i1-22.16.replace('.gif', '.png '); // find first instance of ") after (", chop from string
O = oOld;
O. style. writingMode = 'lr-tb'; // Has to be applied so filter "has layout" and is displayed. Seriously. Refer to http://msdn.microsoft.com/workshop/author/filter/reference/filters/alphaimageloader.asp? Frame = true
O. style. filter = "progid:" + filterID + "(src = '" + newSrc + "', sizingMethod = 'crop ')";
// Replace the old (existing) with the new (just created) element.
// OOld. parentNode. replaceChild (o, oOld );
} Else if (oOld. nodeName = 'img '){
Var newSrc = oold.getattribute('src').replace('.gif', '.png ');
// Apply filter
OOld. src = 'none.gif '; // get rid of image
OOld. style. filter = "progid:" + filterID + "(src = '" + newSrc + "', sizingMethod = 'crop ')";
OOld. style. writingMode = 'lr-tb'; // Has to be applied so filter "has layout" and is displayed. Seriously. Refer to http://msdn.microsoft.com/workshop/author/filter/reference/filters/alphaimageloader.asp? Frame = true
}
}

This.png Method = function (o ){
// Native transparency support. Easy to implement. (woo !)
BgImage = this. getBackgroundImage (o );
If (bgImage ){
// Set background image, replacing. gif
O. style. backgroundImage = 'url('{bgimage.replace('.gif ', '.png') + ')';
} Else if (o. nodeName = 'img '){
O. src = o.src.replace('.gif ', '.png ');
} Else if (! This. isMac ){
// Window. status = 'pnghandler. applyPNG (): Node is not a DIV or IMG .';
}
}

This. getBackgroundImage = function (o ){
Var B, i1; // background-related variables
Var bgUrl = null;

If (o. nodeName = 'div '&&! (This. isIE & this. isMac) {// ie: mac PNG support broken for DIVs with PNG backgrounds
If (document. defaultView ){
If (document. defaultView. getComputedStyle ){
B = document. defaultView. getComputedStyle (o, ''). getPropertyValue ('background-image ');
I1 = B. indexOf ('url (') + 4;
BgUrl = B. substr (i1, B. length-i1-1 );
} Else {
// No computed style
}
} Else {
// No default view
}
}
Return bgUrl;
}

This. supportTest = function (){
// Determine method to use.
// IE 5.5 +/win32: filter

If (this. isIE & this. isWin & this. ver >=5.5 ){
// IE proprietary filter method (via DXFilter)
Self. transform = self. filterMethod;
} Else if (! This. isIE & this. ver <5 ){
Self. transform = null;
// No PNG support or broken support
// Leave existing content as-is
} Else if (! This. isIE & this. ver> = 5 | (this. isIE & this. isMac & this. ver> = 5) {// version 5 + browser (not IE), or IE: mac 5 +
Self. transform = self.png Method;
} Else {
// Presumably no PNG support. GIF used instead.
Self. transform = null;
Return false;
}
Return true;
}

This. init = function (){
If (this. supportTest ()){
This. elements = this. getElementsByClassName ('png ');
For (var I = 0; I <this. elements. length; I ++ ){
This. transform (this. elements [I]);
}
}
}

}

// Instantiate and initialize PNG Handler

Var pngHandler = new PNGHandler ();

DEMO page HTML code:
<Html>
<Head>
<Title> Schillmania! | Png. js demo </title>
<Script type = "text/javascript" src = "png. js"> </script>
</Head>

<Body>

<! --

Don't copy this part here, this is just for your information.

// Required under the
<Script type = "text/javascript" src = "png. js"> </script>

// Required in the <body> tag:



// .. Where XXX and YYY are the width/height of your image. Without width/height the PNG won't work under IE: win32.

// Required before the </body> tag (but after all of your content ):

<Script type = "text/javascript">
PngHandler. init ();
</Script>

// This javascript block shocould be put at the bottom of your page, inside the <body> and before </body>.
// It callthe library and replaces the GIF images (if applicable) before the page has loaded (and before the GIF has loaded, so the user doesn't load 2 images for each PNG you want to replace .)
// If you don't put it after all of your content, it may do strange things and miss some images.

-->

<H1> PNG (img)


<H1> PNG (div with background image)
<Div class = "png" style = "width: 220px; height: 100px; background-image: url(foo.gif); background-repeat: no-repeat">

</Div>

<Script type = "text/javascript">
PngHandler. init ();
</Script>

</Body>
</Html>

Package and download the source code and DEMO:
Local download

Related Article

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.