君语贤
时光静好,与君语;细水流年,与君同;繁华落尽,与君老...

首页>前端设计>JS>正文

网页中图片自动按比例缩放

2019-05-04

对于单个页面中的图片需要应对不同尺寸的设备时候,就要求图片能够自动按比例缩放,对于单页来说,直接写成比例即可,对于内容页而言,也可直接在css中定位内容页图片样式,强制按照百分比缩放,这里讲下另外一种方式,用js判断:

<scriptlanguage="JavaScript">
<!--
//图片按比例缩放
varflag=false;
functionDrawImage(ImgD,iwidth,iheight){
//参数(图片,允许的宽度,允许的高度)
varimage=newImage();
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>

直接将以上脚本放置文章模板中即可。

图文推荐
热门标签
分词技术JavaScript分词脚本文本分析内容插入判断调用CNZZ