jquery实现页面图片等比例放大缩小功能

  html代码结构:

  

复制代码 代码如下:

  <a href=""><img src="images/tmp_376x470.jpg" width="300" height="300" alt=""/></a>

  <a href=""><img src="images/tmp_409x265.jpg" width="300" height="300" alt=""/></a>

  <a href=""><img src="images/tmp_572x367.jpg" width="300" height="300" alt=""/></a>

  样式:

  

复制代码 代码如下:

  a{width:300px;height:300px;background:#fff;border:1px solid #666;display:inline-block} /* 这里需要指定a标签的高宽,背景和边框为可选 */

  脚本(jquery可自行添加):

  

复制代码 代码如下:

  $(function () {

  var imgs = $('a>img');

  imgs.each(function () {

  var img = $(this);

  var width = img.attr('width');//区域宽度

  var height = img.attr('height');//区域高度

  var showWidth = width;//最终显示宽度

  var showHeight = height;//最终显示高度

  var ratio = width / height;//宽高比

  img.load(function () {

  var imgWidth, imgHeight, imgratio;

  $('<img />').attr('src', img.attr('src')).load(function () {

  imgWidth = this.width;//图片实际宽度

  imgHeight = this.height;//图片实际高度

  imgRatio = imgWidth / imgHeight;//实际宽高比

  if (ratio > imgRatio) {

  showWidth = height * imgRatio;//调整宽度太小

  img.attr('width', showWidth).css('margin-left', (width - showWidth) / 2);

  } else {

  showHeight = width / imgRatio;//调高度太小

  img.attr('height', showHeight).css('margin-top', (height - showHeight) / 2);

  }

  });

  });

  });

  });

  这样就是实现了图片的等比例放大缩小了。