jQuery function to resize a set of images to a given area (not height or width)

 ̄綄美尐妖づ 提交于 2019-12-12 12:15:35

问题


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.


回答1:


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)});
});



回答2:


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.



来源:https://stackoverflow.com/questions/8208696/jquery-function-to-resize-a-set-of-images-to-a-given-area-not-height-or-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!