PNGHandler-借助JS让PNG图在IE下实现透明(包括背景图)


Posted in Javascript onAugust 31, 2007

PNG.JS代码:
// 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!)
// Should 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-2).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.pngMethod = 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.pngMethod;
 } 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页HTML代码:
<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 <head> tag:

 <script type="text/javascript" src="png.js"></script>

 // Required in the <body> tag:

 <img src="your-image.gif" class="png" style="width:XXXpx;height:YYYpx" />

 // ..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 should be put at the bottom of your page, inside the <body> and before </body>.
 // It calls the 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>

<img src="foo.gif" alt="" class="png" style="width:220px;height:100px" />

<h1>PNG (div with background image)</h1>

<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>

源码及DEMO打包下载:
本地下载

Javascript 相关文章推荐
使用JS CSS去除IE链接虚线框的三种方法
Nov 14 Javascript
js中的getAttribute方法使用示例
Aug 01 Javascript
jquery实现textarea输入框限制字数的方法
Jan 15 Javascript
详解angularjs结合pagination插件实现分页功能
Feb 10 Javascript
Easyui ueditor 整合解决不能编辑的问题(推荐)
Jun 25 Javascript
Vue学习之路之登录注册实例代码
Jul 06 Javascript
vue+swiper实现侧滑菜单效果
Dec 28 Javascript
浅谈js获取ModelAndView值的问题
Mar 28 Javascript
Vue中Table组件Select的勾选和取消勾选事件详解
Mar 19 Javascript
原生JavaScript实现滑动拖动验证的示例代码
Dec 06 Javascript
在vue项目中 实现定义全局变量 全局函数操作
Oct 26 Javascript
详解Vue的列表渲染
Nov 20 Vue.js
给Javascript数组插入一条记录的代码
Aug 30 #Javascript
用javascript实现给出的盒子的序列是否可连为一矩型
Aug 30 #Javascript
Expandable &quot;Detail&quot; Table Rows
Aug 29 #Javascript
出现“不能执行已释放的Script代码”错误的原因及解决办法
Aug 29 #Javascript
推荐一些非常不错的javascript学习资源站点
Aug 29 #Javascript
070823更新的一个[消息提示框]组件 兼容ie7
Aug 29 #Javascript
找到了一篇jQuery与Prototype并存的冲突的解决方法
Aug 29 #Javascript
You might like
解决了Ajax、MySQL 和 Zend Framework 的乱码问题
2009/03/03 PHP
如何取得中文字符串中出现次数最多的子串
2013/08/08 PHP
详解PHP导入导出CSV文件
2014/11/03 PHP
thinkphp微信开之安全模式消息加密解密不成功的解决办法
2015/12/02 PHP
PHP设计模式之注册树模式分析
2018/01/26 PHP
javascript 去字符串空格终极版(支持utf8)
2009/11/14 Javascript
各种页面定时跳转(倒计时跳转)代码总结
2013/10/24 Javascript
JavaScript使用位运算符判断奇数和偶数的方法
2015/06/01 Javascript
TypeScript 中接口详解
2015/06/19 Javascript
jQuery仿360导航页图标拖动排序效果代码分享
2015/08/24 Javascript
Ionic快速安装教程
2016/06/03 Javascript
xmlplus组件设计系列之列表(4)
2017/04/26 Javascript
QRCode.js:基于JQuery的生成二维码JS库的使用
2017/06/23 jQuery
利用node实现一个批量重命名文件的函数
2017/12/21 Javascript
swiper动态改变滑动内容的实现方法
2018/01/17 Javascript
electron实现qq快捷登录的方法示例
2018/10/22 Javascript
Vue使用.sync 实现父子组件的双向绑定数据问题
2019/04/04 Javascript
vue柱状进度条图像的完美实现方案
2019/08/26 Javascript
详解JavaScript修改注册表的方法
2020/01/05 Javascript
js观察者模式的弹幕案例
2020/11/23 Javascript
Python实现在tkinter中使用matplotlib绘制图形的方法示例
2018/01/18 Python
python如何拆分含有多种分隔符的字符串
2018/03/20 Python
用什么库写 Python 命令行程序(示例代码详解)
2020/02/20 Python
使用Keras实现Tensor的相乘和相加代码
2020/06/18 Python
Python3+Flask安装使用教程详解
2021/02/16 Python
CSS3,线性渐变(linear-gradient)的使用总结
2017/01/09 HTML / CSS
通往英国高街的商店橱窗:Down Your High Street
2020/07/19 全球购物
生物科学专业职业规划书范文
2014/02/11 职场文书
洗发露广告词
2014/03/14 职场文书
学历公证书范本
2014/04/09 职场文书
大班幼儿评语大全
2014/04/30 职场文书
党的群众路线教育实践活动个人对照检查材料(校长)
2014/11/05 职场文书
高校教师个人总结
2015/02/10 职场文书
幼儿园家长反馈意见
2015/06/03 职场文书
评测 | 大屏显示带收音机的高端音箱,JBL TUNE2便携式插卡音箱实测
2021/04/24 无线电
Python 如何实现文件自动去重
2021/06/02 Python