IE6透明PNG解决方案
IE6不支持PNG-24图片一直困扰很多人,但是可以通过IE的独有的滤镜来解决,解决的方案很多,比如:将滤镜写在CSS里,还可以写成单独的 Javascript文件,本来认为推荐两种做法:第一种,将所有PNG图片添加滤镜(此方法有副作用);第二种:有选择性的添加滤镜(推荐);两者都可 以将代码放在单独的JS文件里,然后引用。
第一种:
直接添加如下代码:
function correctPNG() {
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;
}
}
}
function alphaBackgrounds() {
var rslt = navigator.appVersion.match(/MSIE(d+.d+)/, '');
var itsAllGood = (rslt !== null && Number(rslt[1]) >= 5.5);
for (i = 0; i < document.all.length; i++) {
var bg = document.all[i].currentStyle.backgroundImage;
if (bg) {
if (bg.match(/.png/i) !== null) {
var mypng = bg.substring(5, bg.length - 2);
document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src ='" +
mypng + "',sizingMethod='crop')";
document.all[i].style.backgroundImage = "url('')";
}
}
}
}
if (navigator.userAgent.indexOf("MSIE 6.0") > -1) {
window.attachEvent("onload", correctPNG);
window.attachEvent("onload", alphaBackgrounds);
}
第二种:
1)添加以下代码:
var DD_belatedPNG = {
ns: 'DD_belatedPNG',
imgSize: {},
delay: 10,
nodesFixed: 0,
createVmlNameSpace: function () { /* enable VML */
if (document.namespaces && !document.namespaces[this.ns]) {
document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
}
},
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 screenStyleSheet, printStyleSheet;
screenStyleSheet = document.createElement('style');
screenStyleSheet.setAttribute('media', 'screen');
document.documentElement.firstChild.insertBefore(screenStyleSheet, document.documentElement.firstChild.firstChild);
if (screenStyleSheet.styleSheet) {
screenStyleSheet = screenStyleSheet.styleSheet;
screenStyleSheet.addRule(this.ns + '\\:*', '{behavior:url(#default#VML)}');
screenStyleSheet.addRule(this.ns + '\\:shape', 'position:absolute;');
screenStyleSheet.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.screenStyleSheet = screenStyleSheet; /* Add a print-media stylesheet, for preventing VML artifacts from showing up in print (including preview). */
/* Thanks to R閙i Pr関ost for automating this! */
printStyleSheet = document.createElement('style');
printStyleSheet.setAttribute('media', 'print');
document.documentElement.firstChild.insertBefore(printStyleSheet, document.documentElement.firstChild.firstChild);
printStyleSheet = printStyleSheet.styleSheet;
printStyleSheet.addRule(this.ns + '\\:*', '{display: none !important;}');
printStyleSheet.addRule('img.' + this.ns + '_sizeFinder', '{display: none !important;}');
}
},
readPropertyChange: function () {
var el, display, v;
el = event.srcElement;
if (!el.vmlInitiated) {
return;
}
if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
DD_belatedPNG.applyVML(el);
}
if (event.propertyName == 'style.display') {
display = (el.currentStyle.display == 'none') ? 'none' : 'block';
for (v in el.vml) {
if (el.vml.hasOwnProperty(v)) {
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) {
if (this.screenStyleSheet) {
var selectors, i;
selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
for (i=0; i<selectors.length; i++) {
this.screenStyleSheet.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, handlers, handler, moreForAs, a, h;
self = this;
handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
if (el.nodeName == 'A') {
moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
for (a in moreForAs) {
if (moreForAs.hasOwnProperty(a)) {
handlers[a] = moreForAs[a];
}
}
}
for (h in handlers) {
if (handlers.hasOwnProperty(h)) {
handler = function () {
self[handlers[h]](el);
};
el.attachEvent('on' + h, handler);
}
}
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, s;
styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
for (s in styles) {
if (styles.hasOwnProperty(s)) {
el.vml.color.shape.style[s] = el.currentStyle[s];
}
}
},
vmlFill: function (el) {
if (!el.currentStyle) {
return;
} else {
var elStyle, noImg, lib, v, img, imgLoaded;
elStyle = el.currentStyle;
}
for (v in el.vml) {
if (el.vml.hasOwnProperty(v)) {
el.vml[v].shape.style.zIndex = elStyle.zIndex;
}
}
el.runtimeStyle.backgroundColor = '';
el.runtimeStyle.backgroundImage = '';
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;
}
lib = this;
if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
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; margin:0; padding:0;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
imgLoaded = function () {
this.width = this.offsetWidth; /* weird cache-busting requirement! */
this.height = this.offsetHeight;
lib.vmlOffsets(el);
};
img.attachEvent('onload', imgLoaded);
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, size, fudge, makeVisible, bg, bgR, dC, altC, b, c, v;
thisStyle = el.currentStyle;
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};
fudge = (size.L + size.bLW == 1) ? 1 : 0;
/* vml shape, left, top, width, height, origin */
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 );
bg = {'X':0, 'Y':0};
if (el.isImg) {
bg.X = parseInt(thisStyle.paddingLeft, 10) + 1;
bg.Y = parseInt(thisStyle.paddingTop, 10) + 1;
}
else {
for (b in bg) {
if (bg.hasOwnProperty(b)) {
this.figurePercentage(bg, size, b, thisStyle['backgroundPosition'+b]);
}
}
}
el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
bgR = thisStyle.backgroundRepeat;
dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
if (bgR != 'repeat' || el.isImg) {
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 */
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)';
}
},
figurePercentage: function (bg, size, axis, position) {
var horizontal, fraction;
fraction = true;
horizontal = (axis == 'X');
switch(position) {
case 'left':
case 'top':
bg[axis] = 0;
break;
case 'center':
bg[axis] = 0.5;
break;
case 'right':
case 'bottom':
bg[axis] = 1;
break;
default:
if (position.search('%') != -1) {
bg[axis] = parseInt(position, 10) / 100;
}
else {
fraction = false;
}
}
bg[axis] = Math.ceil( fraction ? ( (size[horizontal?'W': 'H'] * bg[axis]) - (size[horizontal?'w': 'h'] * bg[axis]) ) : parseInt(position, 10) );
if (bg[axis] % 2 === 0) {
bg[axis]++;
}
return bg[axis];
},
fixPng: function (el) {
el.style.behavior = 'none';
var lib, els, nodeStr, v, e;
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;
}
lib = DD_belatedPNG;
el.vml = {color: {}, image: {}};
els = {shape: {}, fill: {}};
for (v in el.vml) {
if (el.vml.hasOwnProperty(v)) {
for (e in els) {
if (els.hasOwnProperty(e)) {
nodeStr = lib.ns + ':' + e;
el.vml[v][e] = document.createElement(nodeStr);
}
}
el.vml[v].shape.stroked = false;
el.vml[v].shape.appendChild(el.vml[v].fill);
el.parentNode.insertBefore(el.vml[v].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'; /* 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);
el.vmlInitiated = true;
lib.applyVML(el); /* Render! */
}
};
try {
document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
} catch(r) {}
DD_belatedPNG.createVmlNameSpace();
DD_belatedPNG.createVmlStyleSheet();
2)第二步在调用:
1 <!--[if IE 6]>
2 <script src="js/DD_belatedPNG.js" mce_src="DD_belatedPNG.js"></script>
3 <script type="text/javascript">
4 DD_belatedPNG.fix('.class');//这里是CSS选择,多个就有分号“,”隔开;
5 如:DD_belatedPNG.fix('.class1,.class2,.class3')
6 </script>
7 <![endif]-->
第二种方法使用得比较多,可以根据需要选择滤镜,不会影响其它图片,副作用小。
虽然可以使用滤镜来解决透明的问题,但是这也是有条件的,所使用的图片不能 background-position: 与background-repeat,所以不能从根本解决问题,不过基本可以满足大部分需求了。
IE6透明PNG解决方案的更多相关文章
- 【转载】IE6 PNG透明终极解决方案(打造W3Cfuns-IE6PNG最强帖)
原文地址:http://www.w3cfuns.com/thread-297-1-1.html 本文版权归W3Cfuns.com所有,转载需在文章页面明显位置以链接的方式给出原文链接,否则W3Cfun ...
- IE6下Png透明最佳解决方案(推荐) Unit PNG Fix
引自:http://www.yeeyan.org/articles/view/98510/67784 网络上解决IE6下Png透明解决方案有很多,例如 IE PNG Fix from TwinHeli ...
- IE6 PNG图片不透明的解决方案-tinypng
https://tinypng.com/ 把图片上传上去,就能处理这个问题啦. 纠正一下 再也不用把png图片一个个拖到TinyPNG进行在线压缩(和熊猫哥哥说再见了):再不用把JPG/JPEG图片拖 ...
- IE6 BUG及解决方案
1.IE6中奇数宽高的BUG 一个外部的相对定位div,内部一个绝对定位的div(right:0) 可是在IE6下查看,却变成了right:1px的效果了: 解决方案就是将外部相对定位的div宽度改成 ...
- 前端点击png透明部分解决方案
看效果:点击空白区域红色1.点击实体区域红色2.分别得到颜色数据(包括透明度数据),控制台蓝色1.2.根据颜色数据即可解决png透明部分的点击问题. 让图片不能点击,分两种 1. 整张图片不能点击.这 ...
- 父容器利用opacity设置透明后,子元素跟着变透明的解决方案
背景半透明,子元素不透明的效果经常需要用到.通常对父容器使用opacity属性时,子元素也跟着变透明,所以不妨设置父容器的 background-color:rgba(r,g,b,x); 其中x取值从 ...
- IE6下CSS常见兼容性问题及解决方案
1. 在IE6元素浮动,如果宽度需要内容撑开,就给里面的块元素加浮动. 2. IE6下最小高度问题:在IE6下元素高度小于19px的时候,会被当作19px处理.解决方案:给元素加 overflow:h ...
- ie6背景透明的设置方法 ie6背景颜色透明和png图像透明解决方法
IE6浏览器,让我们又爱又恨.爱它的是,可以让我们写的代码的时候,可以更标准,恨的是,它有太多无厘头的IE6常见bug(详情点击),让我们焦头烂额.现在现在用百度浏览器调查,国内占有率不到6%了,但是 ...
- IE6 的兼容相关问题
因为在实习公司要求兼容IE6+,所以将IE6相关的样式兼容问题列出,及解决方案. 1.让页面变丑的透明背景图片问题: HTML都为以下代码: <div class="img-png&q ...
随机推荐
- 爬虫学习之-git拉取远程错误
本文讲的是把git在最新2.9.2,合并pull两个不同的项目,出现的问题如何去解决 如果合并了两个不同的开始提交的仓库,在新的 git 会发现这两个仓库可能不是同一个,为了防止开发者上传错误,于是就 ...
- vue-cli配置axios,并基于axios进行后台请求函数封装
文章https://www.cnblogs.com/XHappyness/p/7677153.html已经对axios配置进行了说明,后台请求时可直接this.$axios直接进行.这里的缺点是后端请 ...
- BZOJ4974 字符串大师(kmp)
显然最短循环节长度=i-next[i],则相当于给定next数组构造字符串.然后按照kmp的过程模拟即可.虽然这看起来是一个染色问题,但是由图的特殊性,如果next=0只要贪心地选最小的就可以了,稍微 ...
- DAVY的神龙帕夫——读者的心灵故事|十二橄榄枝的传说
再次听Puff的时候我想起了Davy. 文理分班后我坐到了他后面.Davy天生一头黄毛,黑头发”not even one”.上课时他若不是肆无忌惮地舒开四肢呼呼大睡,便是如受惊一般伸长他的细脖子,直挺 ...
- java中初始化块、静态初始化块和构造方法
(所谓的初始化方法init()是另一回事, 在构造方法之后执行, 注意不要混淆) 在Java中,有两种初始化块:静态初始化块和非静态初始化块.它们都是定义在类中,用大括号{}括起来,静态代码块在大括号 ...
- Educational Codeforces Round 33 (Rated for Div. 2) 题解
A.每个状态只有一种后续转移,判断每次转移是否都合法即可. #include <iostream> #include <cstdio> using namespace std; ...
- 【Cogs2187】帕秋莉的超级多项式(多项式运算)
[Cogs2187]帕秋莉的超级多项式(多项式运算) 题面 Cogs 题解 多项式运算模板题 只提供代码了.. #include<iostream> #include<cstdio& ...
- 洛谷 P1858 多人背包 解题报告
P1858 多人背包 题目描述 求01背包前k优解的价值和 输入输出格式 输入格式: 第一行三个数\(K\).\(V\).\(N\) 接下来每行两个数,表示体积和价值 输出格式: 前k优解的价值和 说 ...
- Redis的键值命令、服务器命令
Redis提供了丰富的命令对数据库和各种数据类型进行操作,这些命令可以在Linux 终端使用.在编程时,比如各类语言包,这些命令都有对应的方法. 键值命令 服务器命令 获取数据库中所有键名 >k ...
- innodb--表空间
MySQL把数据库中表结构的定义信息保存到数据库目录的.frm文件中. 在InnoDB中数据库中存储的数据及索引实际是存放在表空间里的(tablespace). 可以将每个基于InnoDB存储引擎的表 ...