js+css完美控制未知尺寸圖片大小

來源:互聯網
上載者:User

 在做網站的時候,往往圖片的處理很重要,固定尺寸容易變形展開,不固定又會有不可預知的問題,有可能撐開頁面。使用js和css講圖片的現實控制在固定的地區內,大於這個地區的等比例縮放,小於這個地區的置中顯示。

看看代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><br /><html xmlns="http://www.w3.org/1999/xhtml"><br /><head><br /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><br /><title>css+js完美控製圖片大小</title><br /><script type="text/javascript" language="JavaScript"><br /><!--<br />var flag=false;<br />function DrawImage(ImgD){<br />var image=new Image();<br />image.src=ImgD.src;<br />if(image.width>0 && image.height>0){<br />flag=true;<br />if(image.width/image.height>= 400/400){<br />if(image.width>400){<br />ImgD.width=400;<br />ImgD.height=(image.height*400)/image.width;<br />}else{<br />ImgD.width=image.width;<br />ImgD.height=image.height;<br />}<br />ImgD.alt=image.width+"x"+image.height;<br />}<br />else{<br />if(image.height>400){<br />ImgD.height=400;<br />ImgD.width=(image.width*400)/image.height;<br />}else{<br />ImgD.width=image.width;<br />ImgD.height=image.height;<br />}<br />ImgD.alt=image.width+"x"+image.height;<br />}<br />}<br />}<br />//--><br /></script><br /><style type="text/css"><br /><!--<br />* {<br />margin:0;<br />padding:0;<br />}<br />li {<br />list-style:none;<br />}<br />img {<br />border:0;<br />}<br />.group_head {<br /> width:400px;<br /> height:400px;<br /> line-height:400px;<br /> border:1px solid #ccc;<br /> overflow:hidden;<br /> position:relative;<br /> text-align:center;<br /> float:left;<br /> margin-right:10px;<br />}<br />.group_head p {<br /> position:static;<br /> +position:absolute;<br /> top:50%;<br /> vertical-align:middle<br />}<br />.group_head img {<br /> position:static;<br /> +position:relative;<br /> top:-50%;left:-50%;<br /> vertical-align:middle<br />}<br />--><br /></style><br /></head></p><p><body><br /><ul class="jobGroup"><br /> <li><a href="../group/index.php?group_id=10011"><div class="group_head"><p><img width="400" height="400" src="http://www.baidu.com/img/baidu_logo.gif" onload="DrawImage(this);"/></p></div></a><br /> </li></p><p> </ul><br /></body><br /></html><br />

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.