[英]background color in image (firefox)
I do something like that to handle a missing image and replace it by background color 我做这样的事情来处理丢失的图像并用背景色替换它
<td width="34"><img onError="handleError(this, '#fff', 'fail');" src="'. $profileImg .'" alt="" height="'.$imgHeight.'" /></td>
And that's the Javascript function that handles that: 这是处理该问题的Javascript函数:
function handleError(elem, colorCode, state){
if ((typeof(elem.onerror) === 'function' && state === 'fail') || (elem.width === 0) ){
elem.style.backgroundColor = colorCode;
console.log(colorCode);
}
}
The console.log line shows that firefox goes in there but won't display the background color ... console.log行显示firefox进入其中,但不显示背景色...
PS: I tried also using JQuery.. PS:我也尝试过使用JQuery。
What am I doing wrong ? 我究竟做错了什么 ?
您的图片带有alt=""
,这意味着在错误时它完全不会在标准模式下显示:图片的行为就像<span>
,而在标准模式下则是alt文本。
I can only assume that your image's $imgHeight
is being set to 0
, ultimately causing the image to not be visible on the page. 我只能假定图像的
$imgHeight
设置为0
,最终导致图像在页面上不可见。
However it's probably not a good idea to use a background as a fallback on the img
element. 但是 ,将背景用作
img
元素的后备可能不是一个好主意。 Different browsers will handle non-loaded images in different ways (a red cross in IE, for example). 不同的浏览器将以不同的方式处理未加载的图像(例如,IE中的红叉标记)。 You'll probably want to assign a background to the image's container:
您可能需要为图像的容器分配背景:
<td class="imgContainer">
<img ... />
</td>
td.imgContainer {
background:#fff;
}
Then simply change your handleError
function to hide the non-loaded image instead. 然后,只需更改
handleError
函数即可隐藏未加载的图像。
Try this (Just save as html file and open in any browser) 试试这个(只需另存为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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.