图片完美缩放
在公司的工作经常要为客户作产品展示的页面,由于客户上传的图片格式大小不一,缩放后会导致变形,于是在星期天抽了点时间,写了一段JS代码,支持图片的完美缩放。
首先给图片加个
标签对,img中不能定义高度或宽度,如下:

在CSS中写入代码:.product_img_div {width:210px;height:190px;overflow:hidden}
作用是控制图片载入时,溢出部分隐藏,这样就不会把界面撑得太难看。
再写JS代码:
[code]ReSizeImg(”product_img”,200,180);
function ReSizeImg(cName,w,h){
var reImgs = document.getElementsByTagName(”img”);
for (j=0;j
if (reImgs[j].height==reImgs[j].width) {
reImgs[j].height=h;reImgs[j].width=w;
} else if (reImgs[j].height>reImgs[j].width) {
reImgs[j].height=h;
} else if (reImgs[j].height
}
}
}
}[/code]
测试后,图片大小完美缩放,也解决了在载入时会把界面撑得很难看的问题。
汗一个~~发现BUG,PJBLOG截取了 [ / i ],并且自动在文章最后补全了 [ / i ],那就使用 j 好了~~[em_20]

07月 31st, 2006 at 11:34:34
你的JS好像没有起到作用吗
08月 8th, 2006 at 13:23:17
谢谢~[em_04]
08月 21st, 2006 at 10:59:21
我写程序时也经常用到图片缩放,一直都用这个JS:
调用时这样:var flag=false;
function DrawImage(ImgD){
var image=new Image();
var FitWidth=400;//图片的最大宽,超过这个值就会自动缩小
var FitHeight=300;//按比例缩小
image.src=ImgD.src;
if(image.width>0 && image.height>0){
flag=true;
if(image.width/image.height>= FitWidth/FitHeight){
if(image.width>FitWidth){
ImgD.width=FitWidth;
ImgD.height=(image.height*FitWidth)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt="";
}
else{
if(image.height>FitHeight){
ImgD.height=FitHeight;
ImgD.width=(image.width*FitHeight)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt="";
}
}
}
” width=300 ONLOAD='javascript:DrawImage(this);' align=center border=0>图片里的宽度是这张图没有超过JS里设定的值的时候所显示的宽度和高度09月 18th, 2006 at 06:22:39
这个也收了
09月 18th, 2006 at 09:15:16
onload是不被其他浏览器支持的,所以不同意你的这种方法!
09月 19th, 2006 at 10:47:48
图片缩放后,小图已经看不清了,只是大小缩放,能否再完美点.谢谢
09月 19th, 2006 at 22:37:20
谢谢,我这个以前没注意。以后也用你这个JS来试试