Cross-Browser Variable Opacity with PNG_经验交流
Periodically, someone tells me about the magic of PNG, how it's the ideal image format for the web, and that someday we'll all be using it on our sites instead of GIF. People have been saying this for years, and by now most of us have stopped listening. Sadly, flaky browser support has made PNG impractical for almost everything; but now, with a few simple workarounds, we can finally put one of its most compelling features to use.
PNG? What?
The Portable Network Graphics, or PNG (pronounced “ping”), image format has been around since 1995, having cropped up during the now long-forgotten GIF scare, when Compuserve and Unisys announced they would begin charging royalties for the use of the GIF image format.
To provide GIF support in their applications, software makers like Adobe and Macromedia must pay royalty fees – fees which are passed down to the end user in the selling cost of the software.
When PNG appeared on the scene, web designers were ready to make the switch to the free, superior format and shun GIF forever. But over time, browsers continually failed to support PNG, and eventually most people started to forget about it. Today, nearly everyone still uses GIF habitually.
Which is a shame, because PNG makes GIF look pretty pathetic: it supports gamma correction, (sometimes) smaller file sizes, loss-less compression, up to 48-bit color, and, best of all, true alpha transparency.
To get why alpha transparency is a big deal, we must first understand one of the most annoying limitations of GIF.
Binary Transparency: the Scourge of GIF
When it comes to transparency, GIF doesn't cut it. Whereas PNG supports alpha transparency, GIF only supports binary transparency, which is a big limitation and has a couple of important implications.
For one, a GIF image can either use no transparent colors at all or have one color that's completely transparent – there are no degrees of transparency.
And if a complex GIF does contain a transparent color, the background color of the web page must match the transparent color, or else the anti-aliased area around the transparent color will be surrounded by ugly haloing and fringing. If you've spent more than five minutes as a web designer, you know what I'm talking about.
The result is that any anti-aliased transparent GIF is inextricably tied to the background color of the web page on which it lives. If you ever decide to change that color, you must also change the GIF.
Miraculously, PNG doesn't behave that way. A PNG can be transparent in varying degrees – in other words, it can be of variable opacity. And a transparent PNG is background-independent: it can live on any background color or image. Say you want your navigation on monkeys-run-amuck.com to be 65% opaque so you can see through it to your orangutan background image. You can do that. A transparent anti-aliased “Gorillas, Chimps, Gibbons, et al” title that can sit on top of any background color or image? You can do that, too.
So What About Browser Support?
By now, of course, we'd all be up to our ears in PNGs if browsers supported them reliably. But seven years after the format's inception, you still can't slap a PNG onto a web page like you can a GIF or JPG. It's disgraceful, but not as bad as it sounds.
It turns out that most of the latest versions of the major browsers fully support alpha transparency with PNG – namely, Netscape 6, Opera 6, and recently-released Mozilla 1, all on Windows; and, for the Mac, Internet Explorer 5, Netscape 6, Opera 5, Mozilla 1, OmniWeb 3.1, and ICab 1.9. Incredibly, PNG even works on Opera 6 for Linux, on WebTV, and on Sega Dreamcast.
Now, what's missing from that list?
IE5.5+/Win, bless its heart, will, in fact, display a PNG, but it doesn't natively support alpha transparency. In IE5.5+/Win, the transparent area of your PNG will display at 100% opacity – that is, it won't be transparent at all.
Bugger. So what do we do now?
Proprietary Code-o-Rama: the AlphaImageLoader
Filter
IE4+/Win supports a variety of non-standard, largely ridiculous visual filters that you can apply to any image's style. You can, for instance, fade in an image with a gradient wipe, or make it stretch from nothing to full size, or even make it swipe into place circularly, like a scene change in Star Wars.
A non-pointless gem among these is the AlphaImageLoader
filter, which is supported in IE5.5+/Win. When used to display a PNG, it allows for full alpha transparency support. All you have to do is this:
<DIV ID="myDiv" STYLE="position:relative; height:250px; width:250px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader<SPAN class=linewrap>»</SPAN> (src='myimage.png',sizingMethod='scale');"></DIV>
(Line wraps are marked ». –Ed.)
And you're in business. Perfect alpha transparency. This code works great, with only the small drawback that it's not part of any accepted web standard, and no other browser on the planet understands it.
Serving up PNGs with JavaScript
So the trick is to determine the user's browser and serve up the images appropriately: if IE5.5+/Win, then we use AlphaImageLoader
; if a browser with native PNG support, then we display PNGs the normal way; if anything else, then we display alternate GIFs, because we can't be sure that a PNG will display correctly or at all.
Using a slightly tweaked version of Chris Nott's Browser Detect Lite, we set some global variables to this effect that we can use later on.
// if IE5.5+ on Win32, then display PNGs with AlphaImageLoader if ((browser.isIE55 || browser.isIE6up) && browser.isWin32) { var pngAlpha = true; // else, if the browser can display PNGs normally, then do that } else if ((browser.isGecko) |<span class="linewrap">»</span> | (browser.isIE5up && browser.isMac) |<span class="linewrap">»</span> | (browser.isOpera && browser.isWin <span class="linewrap">»</span> && browser.versionMajor >= 6) |<span class="linewrap">»</span> | (browser.isOpera && browser.isUnix <span class="linewrap">»</span> && browser.versionMajor >= 6) |<span class="linewrap">»</span> | (browser.isOpera && browser.isMac <span class="linewrap">»</span> && browser.versionMajor >= 5) |<span class="linewrap">»</span> | (browser.isOmniweb && <span class="linewrap">»</span> browser.versionMinor >= 3.1) |<span class="linewrap">»</span> | (browser.isIcab && <span class="linewrap">»</span> browser.versionMinor >= 1.9) |<span class="linewrap">»</span> | (browser.isWebtv) |<span class="linewrap">»</span> | (browser.isDreamcast)) { var pngNormal = true; }
(Note for the faint of heart: complete source code for all the examples we cover is available at the end of the article.)
Tactic 1: Quick and Dirty with document.writes
The simplest, most reliable way to spit out PNGs is using inline document.writes based on the above detection. So we use a function like this:
function od_displayImage(strId, strPath, intWidth, <span class="linewrap">»</span> intHeight, strClass, strAlt) { if (pngAlpha) { document.write('<div style="height:'+intHeight+'px;<SPAN class=linewrap>»</SPAN> width:'+intWidth+'px;<SPAN class=linewrap>»</SPAN> filter:progid:DXImageTransform.Microsoft.AlphaImageLoader<SPAN class=linewrap>»</SPAN> (src=\''+strPath+'.png\', sizingMethod=\'scale\')" <SPAN class=linewrap>»</SPAN> id="'+strId+'" class="'+strClass+'"></div>'); } else if (pngNormal) { document.write('<img src="'+strPath+'.png" <SPAN class=linewrap>»</SPAN> width="'+intWidth+'"<SPAN class=linewrap>»</SPAN> height="'+intHeight+'" name="'+strId+'" <SPAN class=linewrap>»</SPAN> border="0" class="'+strClass+'" alt="'+strAlt+'" />'); } else { document.write('<img src="'+strPath+'.gif" <SPAN class=linewrap>»</SPAN> width="'+intWidth+'"<SPAN class=linewrap>»</SPAN> height="'+intHeight+'" name="'+strId+'" <SPAN class=linewrap>»</SPAN> border="0" class="'+strClass+'" alt="'+strAlt+'" />'); } }
Now we can call the od_displayImage function from anywhere on the page. Any JavaScript-capable browser will display an image, and, if we want to be really careful, we can accompany each call with a
It's a time-tested method, but what if we want more control over our PNGs?
Tactic 2: the Beauty & Majesty of Objects
When I told the programmer in the office next door that I was writing this article, he took one look at my code, glowered at me, and said, “Fool. Where's the abstraction? You need to use objects.”
So now we have a JavaScript object to display PNGs. Here's how we use it:
<html><head> <script language="javascript" src="browserdetect_lite.js" type="text/javascript"> </script> <script language="javascript" src="opacity.js" type="text/javascript"></script> <script type="text/javascript"> var objMyImg = null; function init() { objMyImg = new OpacityObject('myimg','/images/myimage'); objMyImg.setBackground(); } </script> <style type="text/css"> #myimg { background: url('back.png') repeat; position:absolute; left: 10px; top: 10px; width: 200px; height: 200px; } </style> </head> <body onload="init()" background="back.jpg"> <div id="myimg"></div> </body> </html>
That's it. The cool thing about the OpacityObject is that we just pass it a DIV ID and an image path and we're done. Using the appropriate technique, it applies the image as a background of the DIV, and from there we can do whatever we want with it. Fill it with text, move it across the screen, resize it dynamically, whatever – just like any other DIV.
The object works in any CSS 1-capable browser that can dynamically apply a background image to a DIV with JavaScript. It's completely flexible, and we could even use it in place of the above function.
The trade-off is that it doesn't degrade as nicely. Netscape 4.7/Win/Mac and Opera 5/Mac, for instance, won't display an image at all. And it has another significant problem, which is this:
IE5/Mac only supports alpha transparency when the PNG resides in an <img>
tag, not when it's set as the background property of a DIV. So PNGs displayed with the OpacityObject will appear 100% opaque in IE5/Mac. This problem is especially frustrating because IE5/Mac is the only browser which natively supports PNG and behaves this way. We've notified Microsoft about this apparent bug and hope for it to be fixed in an upcoming release.
But for now, these issues are the trade-off for flexibility. Obviously, choose the right tactic based on the particular needs of your project. Between them both, you can do pretty much anything with PNGs – like, for instance...
Example 1: Translucent Image on a Photo
In this simple example, we see how the same 80% opaque PNG can be displayed on any kind of background: Translucent Image on a Photo.
Example 2: Anti-Aliased Translucent Navigation with Rollovers
What a beautiful thing it would be, I'm sure you've thought from time to time, to create translucent anti-aliased images that work on any background. Well, check it out: Anti-Aliased Translucent Navigation with Rollovers.
Mouse over the images, observe the behavior of the rollovers, and click “change background” to see how the images behave on different backgrounds. Then view the source. There are a few things worth noting here:
- 为了预加载正确的图像,我们创建一个名为
strExt
的变量,其中包含“.png”或“.gif”。只要我们的 PNG 和备用 GIF 使用相同的名称(文件扩展名除外),浏览器将只预加载实际要使用的图像。 - 我们创建一个名为
pngLink
的类并将光标属性设置为“指针”。当我们调用该函数时,我们将该类名传递给该函数,然后该函数将该类应用于 PNG。结果是,当用户将鼠标悬停在图像链接上时,其指针会变成光标,尽管在 IE5.5+/Win 中,它们实际上只是 DIV。 (您可能还需要将"display:block"
或"display:inline"
添加到您的 PNG 类中,具体取决于您使用图像的方式,以使它们在 Netscape 6 中正确显示。(有关详细信息,请参阅 通过 XHTML 改善生活。) - 我们还使用了几个专门用于显示 PNG 的翻转函数。事实证明,虽然可以使用
AlphaImageLoader
动态交换 PNG,但 IE5.5+/Win 却遇到了困难;它太慢了,对于有效的翻转来说太慢了。更好的方法是将背景颜色应用到包含 PNG 的 DIV - 颜色会透过图像的透明部分发光,而且速度也很快。当我们调用该函数时,我们发送要显示的图像的名称和 HTML 颜色 - IE5.5+/Win 将显示颜色,其他将显示图像。 - 注意这些图像甚至有阴影。你可以在它们后面粘贴任何背景图像或颜色,即使 PNG 是完全透明的,它们看起来仍然很棒。这很酷还是什么?
示例 3:内部有 HTML 文本的浮动半透明 DIV
在前两个示例中,我们使用了策略一中的快速而肮脏的函数。现在,我们希望我们的 PNG 与页面上的其他代码交互,所以这次我们使用 OpacityObject 显示它。
但请记住 - 这种方法有缺点(见上文),其中最令人心碎的是这个示例在 IE5/Mac 上不能完美运行。如果这让你感到痛苦,那么总会有快速而肮脏的功能。否则,请继续阅读。
首先我们创建一个 DIV,给它一个 ID,并为其分配我们想要的任何样式属性 - 高度、宽度、字体系列等。
然后,当我们实例化 OpacityObject 时,我们会传递该 DIV 的 ID。我们也沿着图像路径传递,现在我们有了一个具有半透明背景的 DIV。酷!
接下来,我们在 DIV 中放入一些 HTML 文本,并对其应用另一个不相关的对象方法(该对象与 OpacityObject 无关 – 它可以是您周围的任何代码)。现在我们可以在屏幕上移动半透明 DIV。哎哟! 内部有 HTML 文本的浮动半透明 DIV.
因此我们可以一睹 OpacityObject 的潜力。你们铁杆 CSS/DOM 人,发疯吧。
不透明的-R-You
下载我们介绍的对象、函数和示例的源代码。所有代码都依赖于我们调整后的 Browser Detect Lite 版本,该版本也包含在内。 可变不透明度源代码。
一个 PNG 和一个仅 PNG
这一切都非常令人兴奋,但是,正如许多让 Web 开发人员兴奋的成就一样,让 PNG 在当今的浏览器中工作根本不应该这么难。您可以考虑签署请愿书,以说服 Microsoft 在 Internet Explorer 中提供完整的 PNG 支持。运气好的话,这篇文章很快就会过时。
同时,请在本文的讨论论坛中发布任何改进此代码的想法。例如,PNG 主页 讨论了其他一些应该支持 Alpha 透明度的不起眼的浏览器,但尚未得到验证。如果您可以验证这些声明中的任何一个,或者有任何其他有价值的意见,请告诉我们,我们将相应地更新代码。
资源
- PNG 主页
-
AlphaImageLoader
MSDN 上的筛选页面 -
WebFX 上的 PNG 行为,这是在 IE 中显示 PNG 的另一种方法。涉及使用runtimeStyle 对象。这种方法的缺点是,只有在
<img>
标签内显示 PNG 时,它才能正确显示它,而在 CSS 背景图像

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

如何在Windows11上将PNG转换为JPG在Windows10和11上,您可以使用Microsoft内置的Paint应用程序快速转换图像文件。要在Windows11上将PNG图像转换为JPG,请使用以下步骤:打开文件资源管理器并导航到要转换的PNG图像。右键单击图像并从菜单中选择打开方式>绘制。您的照片或图像会在“画图”应用中打开。注意屏幕底部的文件大小。要将文件从PNG转换为JPG,请单击文件并从菜单中选择另存为>JPEG图片。当文件资源

假设您需要将文件的扩展名从一个扩展名重命名为另一个扩展名,例如jpg到png。这很简单,当然!但是,如果您有多个需要更改扩展名的文件怎么办?或者更糟糕的是,如果这些多个文件也位于多个文件夹和子文件夹中,在一个文件夹中怎么办?好吧,对于一个普通人来说,这可能是一场噩梦。但对于一个极客来说,绝对不是。现在的问题是,你是不是极客。好吧,有了 极客专页的帮助,您绝对是!在本文中,我们通过批处理脚本的方法解释了如何轻松地重命名文件夹内所有文件的扩展名,包括您选择的子文件夹从一个扩展名到另一个扩展名。注意:

我们中的许多人在 Python 代码中一遍又一遍地看到这个代码片段:with open('Hi.text', 'w') as f: f.write("Hello, there") 但是,我们中的一些人不知道 with 有什么用,以及为什么我们需要在这里使用它。在此阅读中,您将找到关于 with 可解决的几乎所有问题。让我们开始吧!首先,让我们考虑一下如果不使用 with 关键字我们需要做什么。在这种情况下,我们需要先打开文件并尝试执行 write。不管成功与否,我们最好在

对于PHP开发者来说,遇到“Undefinedvariable”警告信息是非常常见的一件事情。这种情况通常出现在尝试使用未定义的变量时,会导致PHP脚本无法正常执行。这篇文章将为大家介绍如何解决“PHPNotice:Undefinedvariable:的解决方法in”的问题。造成问题的原因:在PHP脚本中,如果变量未被初始化或赋值,就会产生“Un

png是一种采用无损压缩算法的位图格式。PNG格式有8位、24位、32位三种形式,其中8位PNG支持两种不同的透明形式,24位PNG不支持透明,32位PNG在24位基础上增加了8位透明通道,因此可展现256级透明程度。

PNG是一种常见的图像文件格式,全称为“可移植网络图形”(PortableNetworkGraphics)。它是一种无损压缩格式,旨在取代过去常用的JPEG和GIF格式。PNG格式在1995年由图形设计师ThomasBoutell创建,并在随后的几年里逐渐流行起来。PNG格式的特点是支持高质量的图像压缩,同时保留了图像的细节和色彩信息。与JPEG格式相

把图片弄成png的方法:1、打开ps软件;2、找到需要处理的图片比导入到软件中;3、将图片的背景接色调整为白色;4、选中“魔术橡皮擦”工具,点击图片上需要透明化的背景区域;5、依次点击菜单栏的“文件”-“储存为”,在弹窗的保存格式中选择“png”,导出png格式的图片即可。

png是一种常见的图像文件格式,它是一种无损的压缩格式,也就是说它不会损失图像质量。PNG代表可移植网络图形(PortableNetworkGraphics)。PNG文件格式最初在1996年由一组开发者共同创建,旨在取代一些有限的和低效的文件格式,如GIF。PNG文件格式基于无损压缩算法,利用索引、调色板和灰度图像来存储图像数据。与其他图像格式相比,PN
