2013-03-25 51 views
0

我做这样的事情来处理丢失的图像和背景颜色更换背景颜色(火狐)

<td width="34"><img onError="handleError(this, '#fff', 'fail');" src="'. $profileImg .'" alt="" height="'.$imgHeight.'" /></td> 

这就是今天的JavaScript函数处理是:

 function handleError(elem, colorCode, state){ 
     if ((typeof(elem.onerror) === 'function' && state === 'fail') || (elem.width === 0)){ 
      elem.style.backgroundColor = colorCode; 
      console.log(colorCode); 
     } 
     } 

的console.log行显示,Firefox进入那里,但不会显示背景色...

PS:我也试过使用JQuery ..

我做错了什么?

+1

我想说,你不能设置背景颜色的图像...尝试设置它的TD代替。 – Michi 2013-03-25 09:22:15

回答

1

我只能假设您的图像的$imgHeight设置为0,最终导致图像在页面上不可见。

但是使用背景作为img元素的后备可能不是一个好主意。不同的浏览器会以不同的方式处理未加载的图像(例如,IE中的红叉)。你可能会想一个背景分配给图像的容器:

<td class="imgContainer"> 
    <img ... /> 
</td> 

td.imgContainer { 
    background:#fff; 
} 

然后,只需改变你的handleError功能隐藏的非加载图片来代替。

1

试试这个(只是保存为HTML文件,然后打开在任何浏览器)

<html> 
<head> 
<script type="text/javascript"> 
function handleError(elem, colorCode, state){ 
     if ((typeof(elem.onerror) === 'function' && state === 'fail') || (elem.width === 0)){ 
      elem.style.backgroundColor = 'red';   
      console.log(colorCode); 
     } 
     } 
</script> 
</head> 
<body> 
<div class="q"> 
    <div><img style="widht:200px;height:200px;disply:block;"onError="handleError(this, '#fff', 'fail');" src="'. $profileImg .'" alt="" height="'.$imgHeight.'" /></div> 
</div> 
<body> 
</html> 
2

您的图片有alt=""这意味着,在错误不会在所有的标准模式显示:图片行为就像一个<span>与标准模式内的替代文字。