`
piziwang
  • 浏览: 240037 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

ie6 png透明国外处理方法,支持background-position

阅读更多

网址:http://dillerdesign.com/experiment/DD_belatedPNG/

/**
* 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.dillerdesign.com/experiment/DD_belatedPNG/
* Version: 0.0.7a
* Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
*
* Example usage:
* DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
* DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
**/

/*
PLEASE READ:
Absolutely everything in this script is SILLY.  I know this.  IE's rendering of certain pixels doesn't make sense, so neither does this code!
*/

var DD_belatedPNG = {

	ns: 'DD_belatedPNG',
	imgSize: {},
	
	createVmlNameSpace: function() { /* enable VML */
		if (document.namespaces && !document.namespaces[this.ns]) {
		  document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
		}
		if (window.attachEvent) {
			window.attachEvent('onbeforeunload', function() {
				DD_belatedPNG = null;
			});
		}
	},
	
	createVmlStyleSheet: function() { /* style VML, enable behaviors */
		/*
			Just in case lots of other developers have added
			lots of other stylesheets using document.createStyleSheet
			and hit the 31-limit mark, let's not use that method!
			further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
		*/
		var style = document.createElement('style');
		document.documentElement.firstChild.insertBefore(style, document.documentElement.firstChild.firstChild);
		var styleSheet = style.styleSheet;
		styleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
		styleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
		styleSheet.addRule('img.' + this.ns + '_sizeFinder', 'behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;'); /* large negative top value for avoiding vertical scrollbars for large images, suggested by James O'Brien, http://www.thanatopsic.org/hendrik/ */
		this.styleSheet = styleSheet;
	},
	
	readPropertyChange: function() {
		var el = event.srcElement;
		if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
			DD_belatedPNG.applyVML(el);
		}
		if (event.propertyName == 'style.display') {
			var display = (el.currentStyle.display == 'none') ? 'none' : 'block';
			for (var v in el.vml) {
				el.vml[v].shape.style.display = display;
			}
		}
		if (event.propertyName.search('filter') != -1) {
			DD_belatedPNG.vmlOpacity(el);
		}
	},
	
	vmlOpacity: function(el) {
		if (el.currentStyle.filter.search('lpha') != -1) {
			var trans = el.currentStyle.filter;
			trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
			el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
			el.vml.image.fill.opacity = trans; /* complete guesswork */
		}
	},
	
	handlePseudoHover: function(el) {
		setTimeout(function() { /* wouldn't work as intended without setTimeout */
			DD_belatedPNG.applyVML(el);
		}, 1);
	},
	
	/**
	* This is the method to use in a document.
	* @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
	**/
	fix: function(selector) {
		var selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
		for (var i=0; i<selectors.length; i++) {
			this.styleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
		}
	},
	
	applyVML: function(el) {
		el.runtimeStyle.cssText = '';
		this.vmlFill(el);
		this.vmlOffsets(el);
		this.vmlOpacity(el);
		if (el.isImg) {
			this.copyImageBorders(el);
		}
	},
	
	attachHandlers: function(el) {
		var self = this;
		var handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
		if (el.nodeName == 'A') {
			var moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
			for (var a in moreForAs) {
				handlers[a] = moreForAs[a];
			}
		}
		for (var h in handlers) {
			el.attachEvent('on' + h, function() {
				self[handlers[h]](el);
			});
		}
		el.attachEvent('onpropertychange', this.readPropertyChange);
	},
	
	giveLayout: function(el) {
		el.style.zoom = 1;
		if (el.currentStyle.position == 'static') {
			el.style.position = 'relative';
		}
	},
	
	copyImageBorders: function(el) {
		var styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
		for (var s in styles) {
			el.vml.color.shape.style[s] = el.currentStyle[s];
		}
	},
	
	vmlFill: function(el) {
		if (!el.currentStyle) {
			return;
		} else {
			var elStyle = el.currentStyle;
		}
		for (var v in el.vml) {
			el.vml[v].shape.style.zIndex = elStyle.zIndex;
		}
		el.runtimeStyle.backgroundColor = '';
		el.runtimeStyle.backgroundImage = '';
		var noColor = (elStyle.backgroundColor == 'transparent');
		var noImg = true;
		if (elStyle.backgroundImage != 'none' || el.isImg) {
			if (!el.isImg) {
				el.vmlBg = elStyle.backgroundImage;
				el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
			}
			else {
				el.vmlBg = el.src;
			}
			var lib = this;
			if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
				var img = document.createElement('img');
				lib.imgSize[el.vmlBg] = img;
				img.className = lib.ns + '_sizeFinder';
				img.runtimeStyle.cssText = 'behavior:none; position:absolute; left:-10000px; top:-10000px; border:none;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
				img.attachEvent('onload', function() {
					this.width = this.offsetWidth; /* weird cache-busting requirement! */
					this.height = this.offsetHeight;
					lib.vmlOffsets(el);
				});
				img.src = el.vmlBg;
				img.removeAttribute('width');
				img.removeAttribute('height');
				document.body.insertBefore(img, document.body.firstChild);
			}
			el.vml.image.fill.src = el.vmlBg;
			noImg = false;
		}
		el.vml.image.fill.on = !noImg;
		el.vml.image.fill.color = 'none';
		el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
		el.runtimeStyle.backgroundImage = 'none';
		el.runtimeStyle.backgroundColor = 'transparent';
	},
	
	/* IE can't figure out what do when the offsetLeft and the clientLeft add up to 1, and the VML ends up getting fuzzy... so we have to push/enlarge things by 1 pixel and then clip off the excess */
	vmlOffsets: function(el) {
		var thisStyle = el.currentStyle;
		var size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':this.imgSize[el.vmlBg].width, 'h':this.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
		var fudge = (size.L + size.bLW == 1) ? 1 : 0;
		
		/* vml shape, left, top, width, height, origin */
		var makeVisible = function(vml, l, t, w, h, o) {
			vml.coordsize = w+','+h;
			vml.coordorigin = o+','+o;
			vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
			vml.style.width = w + 'px';
			vml.style.height = h + 'px';
			vml.style.left = l + 'px';
			vml.style.top = t + 'px';
		};
		makeVisible(el.vml.color.shape, (size.L + (el.isImg ? 0 : size.bLW)), (size.T + (el.isImg ? 0 : size.bTW)), (size.W-1), (size.H-1), 0);
		makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1);
		
		var bg = {'X':0, 'Y':0};
		var figurePercentage = function(axis, position) {
			var fraction = true;
			switch(position) {
				case 'left':
				case 'top':
					bg[axis] = 0;
					break;
				case 'center':
					bg[axis] = .5;
					break;
				case 'right':
				case 'bottom':
					bg[axis] = 1;
					break;
				default:
					if (position.search('%') != -1) {
						bg[axis] = parseInt(position)*.01;
					}
					else {
						fraction = false;
					}
			}
			var horz = (axis == 'X');
			bg[axis] = Math.ceil(fraction ? ( (size[horz?'W': 'H'] * bg[axis]) - (size[horz?'w': 'h'] * bg[axis]) ) : parseInt(position));
			if (bg[axis] == 0) {
				bg[axis]++;
			}
		};
		for (var b in bg) {
			figurePercentage(b, thisStyle['backgroundPosition'+b]);
		}
		
		el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
		
		var bgR = thisStyle.backgroundRepeat;
		var dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
		var altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
		if (bgR != 'repeat') {
			var c = {'T':(bg.Y), 'R':(bg.X+size.w), 'B':(bg.Y+size.h), 'L':(bg.X)}; /* these are defaults for no-repeat - clips down to the image location */
			if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
				var v = bgR.split('repeat-')[1].toUpperCase();
				c[altC[v].b1] = 1;
				c[altC[v].b2] = size[altC[v].d];
			}
			if (c.B > size.H) {
				c.B = size.H;
			}
			el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
		}
		else {
			el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
		}
	},
	
	fixPng: function(el) {
		el.style.behavior = 'none';
		if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
			return;
		}
		el.isImg = false;
		if (el.nodeName == 'IMG') {
			if(el.src.toLowerCase().search(/\.png$/) != -1) {
				el.isImg = true;
				el.style.visibility = 'hidden';
			}
			else {
				return;
			}
		}
		else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
			return;
		}
		var lib = DD_belatedPNG;
		el.vml = {color: {}, image: {}};
		var els = {shape: {}, fill: {}};
		for (var r in el.vml) {
			for (var e in els) {
				var nodeStr = lib.ns + ':' + e;
				el.vml[r][e] = document.createElement(nodeStr);
			}
			el.vml[r].shape.stroked = false;
			el.vml[r].shape.appendChild(el.vml[r].fill);
			el.parentNode.insertBefore(el.vml[r].shape, el);
		}
		el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
		el.vml.image.fill.type = 'tile'; /* Ze magic!! Makes image show up. */
		el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
		
		lib.attachHandlers(el);
		
		lib.giveLayout(el);
		lib.giveLayout(el.offsetParent);
		
		/* set up element */
		lib.applyVML(el);
	}
	
};
try {
	document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
} catch(r) {}
DD_belatedPNG.createVmlNameSpace();
DD_belatedPNG.createVmlStyleSheet();

 调用Demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
 <style>
.png_bg a{
	display:block;
	width:30px;
	height:42px;
}
.png_bg a:hover{
	background:url(js/tab_r.png);
	text-indent:-2000px;
}
.wrap{
	width:300px;
	height:40px;
	padding:30px;
	background:url(js/bg.jpg);
}
</style>	
<!--[if lte IE 6]>
<script type="text/javascript" src="js/DD_belatedPNG_0.0.7a.js"></script>
<script>
  DD_belatedPNG.fix('.png_bg,.png_bg a:hover');
</script>
<![endif]-->
</head>
<body>
	<h3>DD_belatedPNG 脚本测试.</h3>
	背景图:
	<div class="wrap">
		<div style="background:url(js/tab_r.png);width:30px;height:42px;" class="png_bg"></div>
	</div>

	图片:
	<div class="wrap">
		<img src="js/tab_r.png" width="30" height="42" class="png_bg"/>
	</div>
	
	超链接Hover:
	<div class="wrap png_bg" >
		<a href="#">Hover</a>
	</div>

	背景平铺:
	<div class="wrap">
		<div style="background:url(js/tab_r.png) repeat-x;width:200px;height:42px;" class="png_bg"></div>
	</div>

	背景定位:
	<div class="wrap">
		<div style="background:url(js/tab_r.png) -10px -10px;width:200px;height:42px;" class="png_bg"></div>
	</div>

</body>
</html>

分享到:
评论

相关推荐

    IE6 PNG 透明

    我们知道IE6是不支持透明的PNG的,这无疑限制了网页设计的发挥空间. 然而整个互联网上解决这个IE6的透明PNG的方案也是多不胜数,从使用IE特有的滤镜或是e-xpression, 再到javascript透明GIF替代.但是这些方法都有一个...

    ie(IE) png 半透明 插件

    内含插件及使用说明 ie(IE)png半透明插件使用微软的VML语言对PNG图片进行重新绘制,以达到半透明的效果,并且能支持background-position和background-repeat属性。

    完美解决IE6下png透明

    3. **CSS Sprites**:将多个PNG图像合并成一张大图,通过CSS的`background-position`来显示不同的部分,以此规避IE6的PNG透明问题。这种方法虽然不能解决单个图像的透明性,但可以减少HTTP请求,提高页面加载速度。 ...

    IE6 png透明

    尤其是在处理PNG图像的透明效果时,IE6的表现并不尽如人意。因此,寻找一种方法来解决IE6下的PNG透明问题成为了当时Web开发中的一个热点。 #### 二、IE6 PNG透明问题概述 ##### 2.1 PNG图像格式特性 PNG(Portable...

    IE6png图片透明

    "IE6_PNG_position(定位)&repeat(平铺)_透明解决方案"涉及的关键点是利用JavaScript库(如DD_belatedPNG)来解决IE6对PNG-24透明效果的支持问题,同时结合CSS的"position"属性实现图片的定位,以及"background-...

    ie6 png图片黑边处理办法

    另一个解决方法是利用JavaScript库,如`DD_belatedPNG`,它能为IE6提供PNG透明度支持。引入库后,只需简单调用函数即可: ```html &lt;script src="dd_belatedpng.js"&gt;&lt;/script&gt; &lt;img src="image.png" alt="Image...

    个人CSS设计兼容性问题总结教程

    需要注意的是,修复PNG透明度问题时,使用`background-position`可能导致点击效果失效,因此应尽量避免这种方法。 接着,我们讨论文本框的兼容性。在IE8及以上版本,文本居中显示是默认的,但在IE6和IE7中,可以...

    IE6下PNG背景透明的方法.rar

    在早期的网页设计中,IE6(Internet Explorer 6)浏览器对PNG图片格式的支持存在一些问题,特别是对于PNG-24格式的图片,它无法实现背景透明,这给设计师带来了很大的困扰。PNG-24格式提供了24位颜色深度,支持 ...

    IE6下png图片透明解决方案

    PNG(Portable Network Graphics)是一种支持透明度的高质量图像格式,但在IE6中,PNG-24格式的图片透明度会出现故障,而PNG-8格式虽然能实现简单的透明效果,但色彩表现有限。为了解决这个问题,开发者们提出了一些...

    PNG在IE6下透明

    这种方法需要创建一个专为IE6设计的非透明图片(_ie6.png),然后通过表达式滤镜替换原图。 3. **PNG精灵(Sprite)**:将多个小的PNG图像组合成一个大的PNG精灵图,然后通过改变背景位置显示需要的部分。这种方法...

    在IE6下使PNG透明

    标题“在IE6下使PNG透明”涉及到的是一个古老但仍然重要的Web开发问题,尤其是在处理图形和浏览器兼容性时。PNG(Portable Network Graphics)是一种流行的图像格式,支持24位色彩和透明度,但老版本的Internet ...

    解决IE6.0下png背景透明及连接不能点击

    `ie6-png.htc`是一个行为(Behavior)文件,它包含了处理PNG透明的JavaScript代码。当IE6.0浏览器识别到这个行为时,会应用相应的透明效果。 至于IE6.0下链接不能点击的问题,这通常是因为透明的PNG图片覆盖了链接...

    IE6下PNG图像透明完美解决方案–DD_belatedPNG

    其中一个典型的例子就是在IE6中处理PNG图像的透明问题。由于IE6本身的技术限制,在显示带有透明背景的PNG图像时会出现各种各样的问题。为了解决这一难题,许多开发者投入了大量的精力去寻找合适的解决方案。其中,...

    IE6下png图片透明(qianyunlai.com)

    6. **兼容性优化**:除了基本的透明处理,BelatedPNG还提供了一些额外的功能,如支持CSS的background-position属性,以实现平铺和定位。 使用BelatedPNG库,开发者可以在保持网站设计美观的同时,确保IE6用户也能...

    ie6-png解决方案1

    总的来说,IE6对PNG透明的支持问题可以通过JavaScript库、CSS表达式、CSS精灵等方法来解决,而`iepng.js`是一个实用的解决方案,它能帮助我们在不牺牲设计质量的同时,确保IE6用户也能正常浏览网页。在实际开发中,...

    实现PNG图片在IE6下的背景透明

    1. **CSS滤镜方法**:IE6支持CSS滤镜,可以利用它来实现PNG的透明效果。例如,对于一个ID为"imgId"的PNG图片,可以添加以下CSS样式: ```css #imgId { filter: progid:DXImageTransform.Microsoft....

    IE6实现PNG背景透明

    在早期的网页设计中,IE6(Internet Explorer 6)是一个常见的浏览器,但它对某些现代CSS特性的支持并不完善,特别是在处理PNG图像的透明度方面。PNG格式支持半透明效果,但在IE6下,PNG-24图像会出现背景不透明的...

    使png图片在网页中显示为透明

    在网页设计中,PNG图像格式因其支持透明度而广受欢迎,尤其在需要半透明或精确裁剪背景的情况下。然而,有时我们可能会遇到PNG图片在网页上显示为非透明或者显示为GIF图片的问题。本教程将详细介绍如何确保PNG图片在...

    css 半透明 让IE6支持png图片半透明解决方法

    在网页设计中,IE6浏览器对PNG24格式的透明图片支持不足是一个长期困扰开发者的问题。PNG24格式的图片在IE6下,其透明部分会被渲染为灰色,严重影响了设计效果。本文将探讨几种解决IE6浏览器PNG图片半透明问题的方法...

Global site tag (gtag.js) - Google Analytics