让图片自适应,在开发项目经常会碰到。之前更多的是使用.Net后台来控制。最近有个项目等项目几乎全部完工了才提出这样的要求。
于是想了很多办法,最后用Javascript为主来实现。 闲话不说,步骤主要如下
1. 创建 myFunctions.js
//=======================Begin
// JavaScript Document
function AutoResizeImage(maxWidth,maxHeight,objImg){
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth ==0 && maxHeight==0){
Ratio = 1;
}else if (maxWidth==0){//
if (hRatio<1) Ratio = hRatio;
}else if (maxHeight==0){
if (wRatio<1) Ratio = wRatio;
}else if (wRatio<1 || hRatio<1){
Ratio = (wRatio<=hRatio?wRatio:hRatio);
}
if (Ratio<1){
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
}
function centerImage(imgD, maxWidth, maxHeight){
var div = imgD.parentNode;//获取包含本图片的div
if(imgD.height < maxHeight){
var top = (maxHeight - imgD.height) / 2;
div.style.marginTop = top + "px";
}
if(imgD.width < maxWidth){
var left = (maxWidth - imgD.width) / 2;
div.style.marginLeft = left + "px";
}
}
//===================End
2. 在XXX.aspx 页面中使用
a) 前台页面引入
<script type="text/javascript" src="Scripts/myFunctions.js"></script>
<img runat="server" id="imgNewsId" src="images/newsDefault.jpg" width="212" height="142"
align="left" class="pic_news01" />
b) 后台页面中
page_load(...)
{
imgNewsId.Attributes.Add("onload"," AutoResizeImage(212,142,this);centerImage(this, 212,142)");
//AutoResizeImage(212,142,this) // 按照w/h:212,142成比例缩放
//centerImage 位于Div层的水平,垂直居中
}
补充: 其实理论上直接在前台,在<img >中 <img onload=""> 就可以了