jQuery函数将一组图像调整为给定区域(不是高度或宽度)

我正在尝试编写一个jQuery函数,它将根据指定的区域调整一组图像,而不是简单地调整最大高度或宽度。

这里有一个类似的问题: 按区域调整图像大小 ,但我想让它在jquery中同时使用多个图像

以下是我目前正在使用的内容: http : //jsfiddle.net/szSE5/21/ – 它的function与我目前的预期不同。

这个怎么样:

jQuery.fn.resizeImgByArea = function(avgDimension){ var $this = $(this), oldW = $this.width(), oldH = $this.height(), RatiO = new Number(oldW/oldH), newH = new Number(Math.round(Math.sqrt(avgDimension/RatiO))), newW = new Number (Math.round(newH * RatiO)); $this.css({ width: newW + 'px', height: newH + 'px' }); } $(document).ready(function() { $('#images img').each(function(){$(this).resizeImgByArea(10000)}); }); 

在你的小提琴: http : //jsfiddle.net/szSE5/21/

 jQuery.fn.resizeImgToArea = function(area) { this.each(function() { var imgElement = $(this); var originalWidth = imgElement.width(); var originalHeight = imgElement.height(); var aspectRatio = originalWidth / originalHeight; var newHeight = Math.round(Math.sqrt(area/aspectRatio)); var newWidth = Math.round(aspectRatio * newHeight); imgElement.width(newWidth); imgElement.height(newHeight); }); return this; }; 

乍一看,你的jsfiddle解决方案无法正常工作,因为你的上下文中的“this”是一个直接的DOM元素,而不是jQuery对象。