jQuery function to resize a set of images to a giv

2019-06-28 05:11发布

I'm trying to write a jQuery function that will resize a set of images according to a specified area, rather than simply a max height or width.

There's a similar question here: resize image by area, but I'd like to get it working in jquery and with multiple images at the same time

Here's what I'm currently working with: http://jsfiddle.net/szSE5/21/ — it's not functioning the way I intended at the moment.

2条回答
可以哭但决不认输i
2楼-- · 2019-06-28 05:51

How about this:

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)});
});
查看更多
该账号已被封号
3楼-- · 2019-06-28 06:10

In your fiddle: 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;
};

At first glance, your jsfiddle solution is not working because "this" in your context is a straight-up DOM element, not a jQuery object.

查看更多
登录 后发表回答