叁柒設計 三七设计 Three seven design
详细信息
来自:关键字:

JS让图片自动缩放

  September 09th,2009 13:11:16   Category : Javascript
 Click (1848)

对于不指定大小的图片默认是以原大小显示,所以在不指定大小的图片上用onload事件触发脚本代码,在代码中判断图片的尺寸,如果超过指定值,将自动设置为允许的最大值。

<script language="JavaScript">
<!--
//图片按比例缩放
var flag=false;
function DrawImage(ImgD,iwidth,iheight){
//参数(图片,允许的宽度,允许的高度)
var image=new Image();
image.src=ImgD.src;
if(image.width>0 && image.height>0){
flag=true;
if(image.width/image.height>= iwidth/iheight){
if(image.width>iwidth){
ImgD.width=iwidth;
ImgD.height=(image.height*iwidth)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"×"+image.height;
}
else{
if(image.height>iheight){
ImgD.height=iheight;
ImgD.width=(image.width*iheight)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"×"+image.height;
}
}
}
//-->
</script>

调用:<img src="images/toplogo.gif" onload="javascript:DrawImage(this,100,100)">

[ 资讯评论 ]
暂时没有任何评论!
[ 提交评论 ]
请选择表情
  • 昵称:
  • *
  • 验证码:
  • *点击更换验证码
  • 尚能输入个字符
申明:本网站部分分享内容来自网络,如有侵权请及时与我联系,谢谢,另网友评论仅代表个人观点,与本站立场无关,如果在评论中发表违反我国任何法律的,请即时与我们联系(QQ:77132915),我们将立即予以删除. [ 注:提交评论后,通过审核后方能在网站上显示!]