加载前调整图像大小 - jquery

Not*_*ing 6 html javascript css jquery image

我正在使用这个插件来创建图像缩放和图库,但我想缩放所有图像以适应容器(使用比率算法).

这是比率函数:

function scaleSize(maxW, maxH, currW, currH){
  var ratio = currH / currW;
  if(currW >= maxW && ratio <= 1){
     currW = maxW;
     currH = currW * ratio;
  } else if(currH >= maxH){
     currH = maxH;
     currW = currH / ratio;
  }
  return [currW, currH];
}
Run Code Online (Sandbox Code Playgroud)

这就是画廊加载图片的方式:

 var img = $('<img>').load(function(){
            img.appendTo(a);
            image_container.html(a);
 }).attr('src', src).addClass(opts.big_image_class);
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

 var newSize = scaleSize(300, 320, $(".simpleLens-big-image").width(), $(".simpleLens-big-image").height());
 var img = $('<img>').load(function(){
            img.appendTo(a);
            image_container.html(a);
 }).attr('src', src).addClass(opts.big_image_class).width(newSize[0]).height(newSize[1]);
Run Code Online (Sandbox Code Playgroud)

但是scaleSize由于当前的宽度和高度尚未定义(dom中尚未存在图像),因此无法正常工作.

谢谢你的任何指示.

Mar*_*nst 0

我查看了插件代码,认为你打电话给你scaleSize()太早了。simpleLens-big-image在 var img 设置并addClass()完成后,首先存在带有 class 的图像。尝试以下操作:

var img = $('<img>').load(function(){
           img.appendTo(a);
           image_container.html(a);
}).attr('src', src).addClass(opts.big_image_class);
// at this point img should contain $(".simpleLens-big-image") so we can refer to img
var newSize = scaleSize(300, 320, img[0].naturalWidth, img[0].naturalHeight());
img.width(newSize[0]).height(newSize[1]);
Run Code Online (Sandbox Code Playgroud)