I have seen a number requests and solutions for fixing PNG image
transparency in IE on the list.  However, I have never seen one that
addresses transparency of PNGs when they are used as backgrounds.  I
prefer using elements plus background images for my icons as opposed to
image tags so I can use style sheets to switch icon sets out.  So,
needing to support PNG transparencies in backgrounds I came up with two
possible solutions.

Non-jQuery solution:

I build upon what Klaus already has for supporting transparent PNG
images
(http://www.stilbuero.de/2006/03/15/png-alpha-transparency-fast-and-easy
/)

div.png {
    background-image: expression(
        bg      = this.runtimeStyle.backgroundImage.length > 0 ?
this.runtimeStyle.backgroundImage : this.currentStyle.backgroundImage,

        this.runtimeStyle.backgroundImage = "none",
                src = bg.substring(5,bg.length-2),
                this.runtimeStyle.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',
sizingMethod='scale')"          
    );
}

Problems with this approach (yeah, like you are surprised)
 
1. It can become inefficient.  I my case, my icons appear in an icon bar
that is shown/hidden via a $.slideToggle() effect.  It is initially
hidden, and is shown through a button event.  The above code actually
executes twice the first time the icon bar is displayed.  Then, once for
each time it displayed after the initial call to display.  IMOHO, this
is less than efficient, then again I would expect nothing less from IE.

2. The repeated script calls of the CSS expression made the slide
animation choppy.

The jQuery solution:

The jQuery solution was actually my first solution but I wanted try to
follow Klaus' example using just CSS.  Unfortunately, the "pure" CCS
solution wasn't working for me as well as I felt it should, so I
reverted back to using my plugin.

jQuery.fn.fixPngBackgrounds = function() {
        if($.browser.msie)
    {
        this.each(function () {
                var currentBkg = this.currentStyle.backgroundImage;
                if(currentBkg && currentBkg.length > 0)
                {
                   this.runtimeStyle.backgroundImage = "none"; // Remove
the existing background
                   var urlOnly = currentBkg.substring(5,
(currentBkg.length-2)); // Strip 'url(" and '")'
                   this.runtimeStyle.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + urlOnly +
"', sizingMethod='scale')"
                }
        });
    }   
}


And it's easy to use, just $(".png").fixPngBackgrounds()

I just came up with this today and it appears to be working quite well.
However, any suggestion on improvements or possible gotchas regarding
either approach is more than welcome.

Regards,
-scott

_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/

Reply via email to