IE中多行inline链接的背景图片消失之bug
这个问题也是在制作LSDN的新Theme时发现的。本来我的设想是,针对于文章内的a标签,如果是引用外部链接,则为该链接前加上背景图片以作图示;对于下载地址也是如此。
具体到代码,分别是:
<a href="#" class="download">Floppy Configuration Utility - Intel Matrix Storage Manager</a>
a.download:link, a.download:visited, a.download:hover, a.download:active {
padding-left: 18px;
background: url(icn_download.gif) 3px 4px no-repeat;
}
在Firefox和Opera这些追随W3C的浏览器中,显示毫无问题。

但是在IE中——无论是IE6还是IE7,表现却是让人摸不到头脑——背景图片在链接折行时竟然不见了!

这究竟是为什么?!应该不是代码的错,看来又碰到了IE的bug。果不其然,苦闷很久之后,在“background images lost on multi line inline links”这篇文章中找到了答案。具体原因还请详细阅读这篇文章,总之是现在看起来并没有什么好的办法可以解决,尤其是纯粹的CSS解决方法。而“CSS workaround for external link with small icon”这篇文章中提到的方法由于嵌套了容器,我并不喜欢。算了,看来还是用DOM吧。“Problem with background images on multi line inline links”提供了DOM脚本。我根据自己的需求,做出了一些调整:
var wrapper;
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function getWrapper() {
if (!document.getElementById) return false;
if (!document.getElementsByTagName) return false;
if (!document.createTextNode) return false;
if (document.getElementById("contents")) {
wrapper = document.getElementById("contents");
} else if (document.getElementById("content")) {
wrapper = document.getElementById("content");
} else {
return false;
}
}
function externalLink() {
getWrapper();
var links = wrapper.getElementsByTagName("a");
var imgsrc;
for (i=0; i<links.length; i++) {
if ((links[i].className == "external") || (links[i].className == "download")) {
imgsrc = "icn_" + links[i].className + ".gif";
var newimg = document.createElement("img");
newimg.setAttribute("src",imgsrc);
links[i].insertBefore(newimg,links[i].firstChild);
links[i].className = "ieexternal";
} else {
continue;
}
}
}
addLoadEvent(externalLink);
保存为iefix.js。其中更改className是为了不影响其它浏览器。然后在原有CSS的基础上,增加下面一行:
a.ieexternal:link img, a.ieexternal:visited img,
a.ieexternal:hover img, a.ieexternal:active img {
border: 0;
margin-right: 3px;
margin-top: 2px;
margin-left: 3px;
}
最后在XHTML里加上浏览器限定:
<!--[if IE]>
<script type="text/javascript" src="iefix.js"></script>
<![endif]-->
You can follow any responses to this entry through the RSS 2.0 feed. Responses are currently closed, but you can trackback from your own site.