PNG com transparência no Internet Explorer
Autor/fonte: nick171
E-mail/Url: http://forum.imasters.com.br/index.php?showtopic=223512
Tags: [ png ] [ transparência ]
Estava pesquisando e como muita gente sabe o Internet Explorer tem problemas para exibir PNGs com transparência!
O que acaba forçando a utilizar métodos mais trabalhosos, se matando arrumando uma GIF para não perder qualidade (isso quando fica bom) ou aumentando grosseiramente o código HTML inserindo Flash com a sombra que você quer aonde você quer colocar o efeito de transparência.
Essa técnica eu não sei ao certo em quais versões do IE funcionam, testei no IE 6 e o IE 7 e neles funcionam numa boa.
Agora, vamos ao código.
Deixando todas as PNGs (com excessão dos backgrounds) transparentes
Esse aqui é super fácil, só você jogar um Javascript no código da pagina que ele já lê normalmente:
Arquivo pngfix.js:
Backgrounds PNGs com transparência
Agora esse é para que vocês possam utilizar essas PNGs transparentes como background seja coom class, como ID, diretamente na tag e etc:
E pronto!
O que acaba forçando a utilizar métodos mais trabalhosos, se matando arrumando uma GIF para não perder qualidade (isso quando fica bom) ou aumentando grosseiramente o código HTML inserindo Flash com a sombra que você quer aonde você quer colocar o efeito de transparência.
Essa técnica eu não sei ao certo em quais versões do IE funcionam, testei no IE 6 e o IE 7 e neles funcionam numa boa.
Agora, vamos ao código.
Deixando todas as PNGs (com excessão dos backgrounds) transparentes
Esse aqui é super fácil, só você jogar um Javascript no código da pagina que ele já lê normalmente:
<!--[if lt IE 7]> <script defer type="text/javascript" src="pngfix.js"></script> <![endif]--> <img src="IMAGEM.png" width="300" height="35">
Arquivo pngfix.js:
/*
Correctly handle PNG transparency in Win IE 5.5 & 6.
http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.
Use in <HEAD> with DEFER keyword wrapped in conditional comments:
<!--[if lt IE 7]>
<script defer type="text/javascript" src="pngfix.js"></script>
<![endif]-->
*/
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) && (document.body.filters))
{
for(var i=0; i<document.images.length; i++)
{
var img = document.images[ i ]
var imgName = img.src.toUpperCase()
if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
{
var imgID = (img.id) ? "id='" + img.id + "' " : ""
var imgClass = (img.className) ? "class='" + img.className + "' " : ""
var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
var imgStyle = "display:inline-block;" + img.style.cssText
if (img.align == "left") imgStyle = "float:left;" + imgStyle
if (img.align == "right") imgStyle = "float:right;" + imgStyle
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
img.outerHTML = strNewHTML
i = i-1
}
}
}
Backgrounds PNGs com transparência
Agora esse é para que vocês possam utilizar essas PNGs transparentes como background seja coom class, como ID, diretamente na tag e etc:
<style type="text/css">
<!--
.fundo {
background-image: url(IMAGEM.png);
background-repeat: repeat-y;
width: 100%; /*IMPORTANTE PARA EXEBIR O BACKGROUND PRECISA ESTAR COM UMA LARGURA E/OU ALTURA DEFINIDA */
}
-->
</style>
<!--[if IE]>
<style>
.fundo{
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=IMAGEM.png,sizingMethod='scale');
}
</style>
<![endif]-->
E pronto!

Enviado por xKuRt em 02/05/2007 às 17:43
Avaliação
Avaliação desta publicação: 10.00; Total de avaliações: 2
A avaliação de publicações é restrita a membros cadastrados e logados no nosso site.
Comentários
| Enviado por SleX em 05/02/2009 às 12:40 Seque abaixo alteração no JS passado pelo nosso amigo paa fazer automaticamente as correcoes do backgroundImage os elementos pertinentes, tambem fiz uma auteracao apra tentar funcioanr no IE 5. Ele tambem altera caso seja incluido atravez de class e nao style inline. =] Abração galera. /* Correctly handle PNG transparency in Win IE 5.5 & 6. http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006. Use in <HEAD> with DEFER keyword wrapped in conditional comments: <!--[if lt IE 7]> <script defer type="text/javascript" src="pngfix.js"></script> <![endif]--> Modificado por SleX : http://www.slex.com.br email: sx.slex@gmail.com Incluido correcoes para funcionar com backgroundImage em Elementos */ var TransformerPNG = function(){} if(navigator.appName == "Microsoft Internet Explorer"){ TransformerPNG = function(){ var arVersion = navigator.appVersion.split("MSIE") var version = parseFloat(arVersion[1]) if ((version >= 5) && (document.body.filters) && (version < 7)) { for(var i=0; i<document.images.length; i++) { var img = document.images[i]; var imgName = img.src.toUpperCase(); if (imgName.substring(imgName.length-3, imgName.length) == "PNG") { var imgID = (img.id) ? "id='" + img.id + "' " : "" var imgClass = (img.className) ? "class='" + img.className + "' " : "" var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' " img.style.display = 'inline-block'; var Sstyle = img.style.cssText; var imgStyle = Sstyle; if (img.align == "left") imgStyle = "float:left;" + imgStyle; if (img.align == "right") imgStyle = "float:right;" + imgStyle; if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle; var Ssstyle = " style="" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src='" + img.src + "', sizingMethod='scale');""; var mysstyle = "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src='" + img.src + "', sizingMethod='scale');"; var strNewHTML = "<span " + imgID + imgClass + imgTitle + Ssstyle + "></span>"; //var strNewHTML = "<img src='/static/imgs/pnghack.gif' " + imgID + imgClass + imgTitle + Ssstyle + "/>"; img.outerHTML = strNewHTML; img.setAttribute('style',mysstyle); //alert(strNewHTML); i = i-1 } } for(var i=0; i<document.all.length; i++) { var elm = document.all[i]; var sty = elm.getAttribute('style'); if(sty) { var bgi = sty.getAttribute('backgroundImage'); if(bgi) { if (bgi.toLowerCase().substring(bgi.length-4, bgi.length) == "png)") { bgi = bgi.replace('url(',''); bgi = bgi.replace('URL(',''); bgi = bgi.replace(')',''); bgi = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+bgi+",sizingMethod='crop')"; sty.setAttribute('backgroundImage','none'); sty.setAttribute('filter',bgi); } } } } for(var i=0; i<document.styleSheets.length; i++) { var sheet = document.styleSheets[i]; //for(x in sheet){if(confirm(x)){break}} if(sheet.cssRules){ var rules = sheet.cssRules; } else { var rules = sheet.rules; } for(var ii=0; ii< rules.length; ii++) { var sty = rules[ii].style; if(sty) { //for(x in sty){if(confirm(x)){break}} var bgi = false; var bgi = sty.getAttribute('backgroundImage'); if(bgi) { if (bgi.toLowerCase().substring(bgi.length-4, bgi.length) == "png)") { bgi = bgi.replace('url(',''); bgi = bgi.replace('URL(',''); bgi = bgi.replace(')',''); bgi = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+bgi+",sizingMethod='crop')"; if(sty.setAttribute){ sty.setAttribute('backgroundImage','none'); sty.setAttribute('filter',bgi); } } } } } } } } } var pngfixonload = onload; onload = function(){ if(pngfixonload){ pngfixonload(); /*try{pngfixonload()}catch(e){}*/ } TransformerPNG(); } -- SleX |
| Enviado por wdmr em 28/09/2007 às 05:01 Rafa, acabei de testar e, funcionou no ie 5.5 e no 6. No 5.0 não funcionou. Obrigado Nick171 |
| Enviado por Rafa Ximenes em 05/06/2007 às 10:03 Gostaria de saber se alguém testou isso?? Estou tentando aqui num IE 6, porém, por algum motivo, a primeira imagem que ele encontra, ele some.. a mesma imagem, numa outra posição, não acontece nada... vlw |
Envio de comentário:
Terça, 09 de Fevereiro de 2010
Área restrita
Leitura recomendada
Últimas publicações
Top 5 membros
- Jotah191 pts
- fbinasco163 pts
- fredbcn117 pts
- Nando93 pts
- andersonop81 pts
Últimos membros cadastrados
- thaickerem 09/02
- felipearomaniem 09/02
- LEANDROTIMAO15em 09/02



