码迷,mamicode.com
首页 > 其他好文 > 详细

加载网络未知尺寸图片,自动缩放并水平、垂直居中显示

时间:2016-04-09 18:36:39      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

个人随笔
代码实现以下功能:
1、加载网络未知尺寸的图片,用户可以随意输入显示区的大小,图片会自动适应宽高。
2、水平、垂直居中未知尺寸的图片

1
<!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>水平并垂直居中未知大小的图片</title> 6 <style> 7 #imageBox { 8 width: 250px; 9 height: 250px; 10 margin: 30px auto; 11 border: 1px solid green; 12 display: table; /**key point**/ 13 text-align: center; 14 } 15 16 .spaceSpan { 17 height: 100%; 18 display: table-cell; /**key point**/ 19 vertical-align: middle; /**key point**/ 20 } 21 22 #testImage { 23 vertical-align: middle; 24 } 25 26 </style> 27 <script> 28 function zoomImage(imageId, imageBoxWidth, imageBoxHeight) { 29 var image = document.getElementById(imageId); 30 //计算出图片容器的宽高比 31 var imageBoxWidthHeightScale = imageBoxWidth / imageBoxHeight; 32 //计算出实际图片的宽高比 33 var imageWidthHeightScale = image.width / image.height; 34 var widthScale = image.width / imageBoxWidth; 35 var heightScale = image.height / imageBoxHeight; 36 var maxScale = Math.max(widthScale, heightScale); 37 if (maxScale < 1) { //图片宽高都比盒子小时不对图片操作 38 return null; 39 } else { //图片的宽或者高大于盒子大小时 40 if (imageBoxWidthHeightScale > imageWidthHeightScale) { //盒子相对图片来说更"扁",此时控制图片的高度 41 image.height *= heightScale > 1 ? 1 / heightScale : heightScale; 42 } else { //图片相对盒子来说更"扁",此时控制图片的宽度 43 image.width *= widthScale > 1 ? 1 / widthScale : widthScale; 44 } 45 } 46 } 47 </script> 48 </head> 49 <body> 50 <div id="imageBox"> 51 <span class="spaceSpan"> 52 <image id="testImage" 53 src="http://daily.clzg.cn/res/1/20160311/75231457630062963.jpg" 54 onload="zoomImage(‘testImage‘,200,200)"/> 55 </span> 56 </div> 57 </body> 58 </html>

实际效果如下图:

技术分享

 

加载网络未知尺寸图片,自动缩放并水平、垂直居中显示

标签:

原文地址:http://www.cnblogs.com/Farris/p/5372114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!