Copy codeThe Code is as follows:
<Html>
<Head>
<Title> Untitled </title>
<Style type = "text/css">
. TestCss {width: 200px; height: 300px; border: 1px red solid; text-align: center; display: block ;}
. TestCss1 {width: 300px; height: 300px; border: 1px red solid; text-align: center; display: block ;}
. TestCss2 {width: 400px; height: 300px; border: 1px red solid; text-align: center; display: block ;}
</Style>
<Script type = "text/javascript">
Function autoSizeImg (Contents, offsetWidth, offsetHeight, vlmiddle ){
Var o = Contents. getElementsByTagName ("IMG ");
Var cwidth = window. getComputedStyle? Window. getComputedStyle (Contents, null). width: Contents. currentStyle ["width"];
Var cheight = window. getComputedStyle? Window. getComputedStyle (Contents, null). height: Contents. currentStyle ["height"];
Var ncwidth = parseInt (cwidth );
Var ncheight = parseInt (cheight );
For (var I = 0; I <o. length; I ++ ){
Var img = o [I];
Var iw = img. width;
Var ih = img. height;
If (img. width> ncwidth ){
Var nw = ncwidth-offsetWidth;
Img. width = nw
Img. height = (nw * ih)/iw;
} Else if (img. width <ncwidth & img. height> ncheight ){
Var nh = ncheight-offsetHeight;
Img. height = nh;
Img. width = (nh * iw)/ih;
}
If (img. height> ncheight & img. width <ncwidth ){
Var hh = ncheight-offsetHeight;
Img. height = nh;
Img. width = (nh * iw)/ih;
}
If (vlmiddle) img. style. marginTop = (ncheight-img.height)/2) + "px ";
}
}
</Script>
</Head>
<Body>
<Div class = "testCss">
</Div>
<Div class = "testCss1">
</Div>
<Div> </div>
<Div class = "testCss2">
</Div>
</Body>
</Html>
Note:
1. The following testCss1 and testCss2 styles are the same as testCss. Only the size is set.
2. the height and width of the red part must be defined, which is the height and width of the parent layer container that stores the img.
3. text-algin: horizontally centered
4. display: block, which must be set. Otherwise, enabling auto scaling under FF does not work.
Usage:
1. Define the style at the parent layer of img, including the things mentioned in the above annotations;
2. img and
Onload = "autoSizeImg (this. parentNode, 5, 5, true )"
Parameter description:
The Contents parameter generally uses this. parentNode, even if the img parent is easy
The offsetWidth and offsetHeight parameters are the correction values of the center width and height respectively.
If the vlmiddle parameter is set to true, the center is vertical.
<Html> <pead> <title> Untitled </title> <style type = "text/css">. testCss {width: 200px; height: 300px; border: 1px red solid; text-align: center; display: block ;}. testCss1 {width: 300px; height: 300px; border: 1px red solid; text-align: center; display: block ;}. testCss2 {width: 400px; height: 300px; border: 1px red solid; text-align: center; display: block ;} </style> </pead> <body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]