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

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打包下载:
本地下载

(0)

相关推荐

  • JS解决ie6下png透明的方法实例

    复制代码 代码如下: <!DOCTYPE html><html lang="en"><head><title>解决ie6下png透明方法之JS法-</title><style type="text/css"> .a{background: #FFFF99 ;  background-image: url(bg.jpg); height:800px;padding: 50px;  } .b{ fl

  • 解决IE6的PNG透明JS插件使用介绍

    IE6的PNG透明是个老问题了,最近有朋友问我有没有最好的解决这个问题的插件.虽然知道且在用DD_belatedPNG这个插件,今天抽空把这个发上来. 虽然之前在博客里发过一款jquery的png插件,但是不支持背景平铺. DD_belatedPNG使用了微软的VML语言对PNG图片进行重新绘制,以达到半透明的效果,并且能支持background-position和background-repeat属性,支持伪类.是一款不错的值得推荐的插件,用法也比较简单. 使用方法: 复制代码 代码如下: <

  • nodejs修复ipa处理过的png图片

    最近做项目遇到一个需求:解析apk和ipa包,然后把里面的icon上传到服务器. 问题 解析上传过程比较简单,我使用JSZip对apk和ipa进行解压,然后把找到里面的icon上传到服务器.但是,当我在网页中使用图片时,问题出现了.对于apk中的icon,没有任何问题,但是对于ipa中解析出来的图片,在safari中可以正常显示,在其他任何浏览器去无法显示. 原因 Google后发现,是苹果对png图片进行了优化处理,具体看这篇文章(查看),在文章中我们可以了解到一些有用信息: Apple us

  • ie6下png图片背景不透明的解决办法使用js实现

    我们时常在使用png图片的时候,在ie6下发生背景不透明的问题,下面给大家介绍下一个js解决的方式. 首先我们要用到一个js,代码如下: 复制代码 代码如下: /** * DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>. * Author: Drew Diller * Email: drew.diller@gmail.com * URL: http://www.diller

  • ThinkPHP水印功能实现修复PNG透明水印并增加JPEG图片质量可调整

    本文实例讲述了ThinkPHP水印功能实现修复PNG透明水印并增加JPEG图片质量可调整的方法.分享给大家供大家参考.具体实现方法如下: TP自带有图片类,有给图片加水印的功能. 这里完善了: 1. png水印透明 2. 加水印后质量调整(只限于JPG格式) 代码如下: 复制代码 代码如下: /** +-------------------- * 为图片添加水印 +-------------------- * @static public +-------------------- * @par

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

    PNG.JS代码: // PNGHandler: Object-Oriented Javascript-based PNG wrapper // -------------------------------------------------------- // Version 1.1.20031218 // Code by Scott Schiller - www.schillmania.com // ---------------------------------------------

  • js实现点击图片改变页面背景图的方法

    本文实例讲述了js实现点击图片改变页面背景图的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: <html> <head> <title>点击图片即改变页面的背景图片</title> </head> <body bgcolor="#FFFFFF" leftmargin="0" marginwidth="0"> <script language=&qu

  • js实现点击切换和自动播放的轮播图

    本文实例为大家分享了js实现点击切换和自动播放的轮播图,供大家参考,具体内容如下 轮播图案例 <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0"&

  • vue.js引用背景图background无效的3种解决方案

    目录 效果图预览 1. 正确的代码,示例如下 2. 错误的代码,截图对比 vue添加背景图没反应 #vue.js项目中,出现css调用background背景图无效?如何解决? 或者调用<img>标签,也无效果? 直接上代码,自行对比查找一下: 效果图预览 1. 正确的代码,示例如下 <template> <div class="demo"> <!-- 成功引入的三种方法: --> <!-- 图1 --> <div cl

  • 背景图跟随鼠标移动的Mootools插件实现代码

    效果演示:源代码: 复制代码 代码如下: <script style="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.1/mootools-yui-compressed.js"></script> </head> <body id='a'> <h2 class='a'>Single images</h2

  • 关于Vue背景图打包之后访问路径错误问题的解决

    案例环境 通过vue-cli脚手架创建的vue项目 在项目打包的时候遇到了背景图片路径出错的问题,经过谷歌一番,发现是在配置的时候对图片的限制大小过小造成的 首先,出错点在url-loader上面. // url-loader配置 // build/webpck.base.conf.js { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', query: { limit: 10000, name: utils.assetsP

  • jquery带下拉菜单和焦点图代码分享

    jquery带下拉菜单和焦点图是一款顶部通栏带二级下拉菜单和banner导航菜单代码.感兴趣的朋友快来学习学习吧 运行效果图:                           ----------------------查看效果 下载源码----------------------- 小提示:浏览器中如果不能正常运行,可以尝试切换浏览模式. 为大家分享的jquery带下拉菜单和焦点图如下 <head> <meta http-equiv="Content-Type"

  • js实现的非常棒的绿色下拉透明菜单

    非常棒的绿色下拉透明菜单 var mmenus = new Array(); var misShow = new Boolean(); misShow=false; var misdown = new Boolean(); misdown=false; var mnumberofsub=0; var musestatus=false; var mpopTimer = 0; mmenucolor='#89CB10';mfontcolor='MenuText';mmenuoutcolor='#ADE

  • CSS实现同一背景图的导航菜单

    css实现导航菜单带背景图效果,sky整理收集. ul,li{ list-style:none; float:left;} body{ font-size:12px; line-height:1.6; font-family:Verdana, "宋体", Arial; text-align:center;} #info li{ margin-left:4px; margin-top:15px;} #info a {display:block;text-align:center; pad

  • Android 实现背景图和状态栏融合方法

    我们先看一下代码: public class MainActivity extends AppCompatActivity { ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21){ View decorView = getWindow().getDecorView(); deco

随机推荐