当前位置:Gxlcms > css > css+JavaScript如何控制图片大小的示例代码分享

css+JavaScript如何控制图片大小的示例代码分享

时间:2021-07-01 10:21:17 帮助过:20人阅读

使用js和css讲图片的现实控制在固定的区域内,大于这个区域的等比例缩放,小于这个区域的居中显示。

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  5. <title>css+js完美控制图片大小</title>
  6. <script type="text/javascript" language="JavaScript">
  7. <!--
  8. var flag=false;
  9. function DrawImage(ImgD){
  10. var image=new Image();
  11. image.src=ImgD.src;
  12. if(image.width>0 && image.height>0){
  13. flag=true;
  14. if(image.width/image.height>= 400/400){
  15. if(image.width>400){
  16. ImgD.width=400;
  17. ImgD.height=(image.height*400)/image.width;
  18. }else{
  19. ImgD.width=image.width;
  20. ImgD.height=image.height;
  21. }
  22. ImgD.alt=image.width+"x"+image.height;
  23. }
  24. else{
  25. if(image.height>400){
  26. ImgD.height=400;
  27. ImgD.width=(image.width*400)/image.height;
  28. }else{
  29. ImgD.width=image.width;
  30. ImgD.height=image.height;
  31. }
  32. ImgD.alt=image.width+"x"+image.height;
  33. }
  34. }
  35. }
  36. //-->
  37. </script>
  38. <style type="text/css">
  39. <!--
  40. * {
  41. margin:0;
  42. padding:0;
  43. }
  44. li {
  45. list-style:none;
  46. }
  47. img {
  48. border:0;
  49. }
  50. .group_head {
  51. width:400px;
  52. height:400px;
  53. line-height:400px;
  54. border:1px solid #ccc;
  55. overflow:hidden;
  56. position:relative;
  57. text-align:center;
  58. float:left;
  59. margin-right:10px;
  60. }
  61. .group_head p {
  62. position:static;
  63. +position:absolute;
  64. top:50%;
  65. vertical-align:middle
  66. }
  67. .group_head img {
  68. position:static;
  69. +position:relative;
  70. top:-50%;left:-50%;
  71. vertical-align:middle
  72. }
  73. -->
  74. </style>
  75. </head>
  76. <body>
  77. <ul class="jobGroup">
  78. <li><a href="http://www.gxlcms.com">
  79. <div class="group_head">
  80. <p>
  81. <img width="400" height="400" src="http://www.baidu.com/img/baidu_logo.gif" onload="DrawImage(this);"/>
  82. </p>
  83. </div>
  84. </a>
  85. </li>
  86. </ul>
  87. </body>
  88. </html>


以上就是css+JavaScript如何控制图片大小的示例代码分享的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行