Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 加载前调整图像大小-jquery_Javascript_Jquery_Html_Css_Image - Fatal编程技术网

Javascript 加载前调整图像大小-jquery

Javascript 加载前调整图像大小-jquery,javascript,jquery,html,css,image,Javascript,Jquery,Html,Css,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){

我正在使用创建图像缩放和图库,但我希望缩放所有图像以适应容器(使用比率算法)

下面是比率函数:

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];
}
函数缩放(maxW,maxH,currW,currH){
var比率=电流/电流;
如果(currW>=maxW&&ratio=maxH){
currH=最大值;
currW=电流/比率;
}
返回[当前,当前];
}
这是gallery加载图像的方式:

 var img = $('<img>').load(function(){
            img.appendTo(a);
            image_container.html(a);
 }).attr('src', src).addClass(opts.big_image_class);
var img=$('
我所尝试的:

 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]);
var newSize=scaleSize(300320,$(.simpleLens大图”).width(),$(.simpleLens大图”).height();
变量img=$('
但是
scaleSize
无法正常工作,因为当前的宽度和高度尚未定义(dom中尚未存在图像)


谢谢您的指点。

尝试类似的方法并调用onload方法。这将确保在调整大小之前将图像加载到DOM中

var img = $('<img>');    
img.src = src ;
img.onload = function() {
    // Run onload code.
} ;

var-img=$(“我查看了插件代码,认为您调用
scaleSize()
太早了。设置var-img并完成
addClass()
后,首先存在一个带有类
simpleLens big image
的映像。 请尝试以下操作:

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

var img=$('your
.simpleLens big image
在哪里?很抱歉回复太晚。将
load()
更改为
onload()
会使库停止工作,同时将鼠标悬停在每个图像上。我希望您不介意看一下,这里是插件的脚本,我正在编辑它。
console.log(img.width());
为0,我认为图像在调用其宽度之前已经加载。这就是问题所在。@如果您愿意,请发布
console.log(img[0].naturalWidth)的结果
。好吧!就在这里!它像一个符咒一样有效!谢谢马丁·恩斯特,你救了我一天!@没什么我很高兴的,但我不能保证每个旧浏览器都能在图像上设置
自然宽度/高度属性。