这个图片等比缩放代码造成浏览器崩溃了,怎么办呢?
图片加载完成前使用Loading.gif代替,加载完成后等比缩放;
下面的代码,造成浏览器不断循环发送请求,最后浏览器不堪负荷,崩溃了。
怎么办呢?
问题出于下面注释行中
function imageScale(ImgD,FitWidth,FitHeight){
var holdImg = "../Images/icons/loading.gif";
var image = new Image(),_width,_hegiht;
image.src = ImgD.src;
ImgD.src = holdImg; /* 问题在这行 和 下面最后一行 */
if(image.width>0 && image.height>0){
if(image.width/image.height>= FitWidth/FitHeight){
if(image.width>FitWidth){
_width=FitWidth;
_height=(image.height*FitWidth)/image.width;
}else{
_width=image.width;
_height=image.height;
}
} else{
if(image.height>FitHeight){
_height=FitHeight;
_width=(image.width*FitHeight)/image.height;
}else{
_width=image.width;
_height=image.height;
}
}
}
ImgD.width = _width;
ImgD.height = _height;
ImgD.src = image.src; /* 问题在这行 和前面的注释行 */
}
<img src="http://img.my.csdn.net/uploads/201202/16/266283_1329364024zGY2.jpg" onload="imageScale(this,200,200)" />
[解决办法]
ImgD.src = holdImg; /* 问题在这行 和 下面最后一行 */
onload函数里不能再操作src,否则又会执行onload方法,造成了递归使用,是个死循环!!
[解决办法]
ImgD.onload=null; //删除事件绑定试试
ImgD.src = image.src; /* 问题在这行 和前面的注释行 */
[解决办法]
<script type="text/javascript">
function imageScale(ImgD,FitWidth,FitHeight){
ImgD.onload=null; //删除绑定事件 避免死循环
//var holdImg = "../Images/icons/loading.gif";根本没必要加载效果,因为你是图片加载成功后执行,根本看不到这个图片
var image = new Image(),_width,_hegiht;
image.src = ImgD.src;
//ImgD.src = holdImg; /* 删除 */
if(image.width>0 && image.height>0){
if(image.width/image.height>= FitWidth/FitHeight){
if(image.width>FitWidth){
_width=FitWidth;
_height=(image.height*FitWidth)/image.width;
}else{
_width=image.width;
_height=image.height;
}
} else{
if(image.height>FitHeight){
_height=FitHeight;
_width=(image.width*FitHeight)/image.height;
}else{
_width=image.width;
_height=image.height;
}
}
}
ImgD.width = _width;
ImgD.height = _height;
ImgD.src = image.src;
}
</script>
[解决办法]
加一个afterrender event的监听,图片显示完毕后,则去掉loading.gif。
[解决办法]
<script type="text/javascript">
var pic=document.getElementsByTagName("img");// 最好指定范围的图片,以免全部改了。
var temp,arr=[];//数组
for(var i=0;i<pic.length;i++){
arr[i] = new Image();
arr[i].onload=(function(n){
return function(){
//.........其他代码
pic[n].src=arr[n].src;//图片加载完后,还原图片。必须使用闭包函数!
}
})(i);
temp=pic[i].src;
pic[i].src="http://avatar.profile.csdn.net/6/6/6/1_ftiger.jpg";//加载效果,不管图片有没有加载成功,先替换再说
arr[i].src = temp;//得到原图片地址
}
</script>
