使用jquery获取图像宽度和高度
我有一个非常简单的代码,令人烦恼的是它一直在工作,就我的一生而言,我不明白为什么它现在失败了:使用jquery获取图像宽度和高度,jquery,image,height,width,Jquery,Image,Height,Width,我有一个非常简单的代码,令人烦恼的是它一直在工作,就我的一生而言,我不明白为什么它现在失败了: function imageSize(img){ var theImage = new Image(); theImage.src = img.attr('src'); var imgwidth = theImage.width; var imgheight = theImage.height; alert(imgwidth+'-'+imgheight); } 传递的“img”
function imageSize(img){
var theImage = new Image();
theImage.src = img.attr('src');
var imgwidth = theImage.width;
var imgheight = theImage.height;
alert(imgwidth+'-'+imgheight);
}
传递的“img”变量是img对象,从以下位置获取:
jQuery('img')
.each(function(){
var imgsrc = jQuery(this);
imageSize(imgsrc);
});
好的-当我在JSFIDLE上测试它时,我之前给出的答案是无效的-我创建了这个,但它符合您的要求?是否需要“新图像()”部分给图像一些硬编码的尺寸 我稍微更改了您的代码,因此它可以执行以下操作:
function imageSize(img){
var theImage = new Image(); // ignoring this part when checking the image width/height
theImage.src = img.attr('src');
var imgwidth = $(img).width();
var imgheight = $(img).height();
alert(imgwidth+'-'+imgheight);
}
$('img').each(function(){
var imgsrc = jQuery(this);
imageSize(imgsrc);
});
好的-当我在JSFIDLE上测试它时,我之前给出的答案是无效的-我创建了这个,但它符合您的要求?是否需要“新图像()”部分给图像一些硬编码的尺寸 我稍微更改了您的代码,因此它可以执行以下操作:
function imageSize(img){
var theImage = new Image(); // ignoring this part when checking the image width/height
theImage.src = img.attr('src');
var imgwidth = $(img).width();
var imgheight = $(img).height();
alert(imgwidth+'-'+imgheight);
}
$('img').each(function(){
var imgsrc = jQuery(this);
imageSize(imgsrc);
});
您必须等待图像加载,然后才能访问其大小:
function imageSize(img){
var theImage = new Image();
theImage.onload = function(){
var imgwidth = theImage.width;
var imgheight = theImage.height;
alert(imgwidth+'-'+imgheight);
}
theImage.src = img.attr('src');
}
您必须等待图像加载,然后才能访问其大小:
function imageSize(img){
var theImage = new Image();
theImage.onload = function(){
var imgwidth = theImage.width;
var imgheight = theImage.height;
alert(imgwidth+'-'+imgheight);
}
theImage.src = img.attr('src');
}
图像可能尚未加载。因此,请尝试(未经测试):
图像可能尚未加载。因此,请尝试(未经测试):
那么,到底是什么问题呢?我看没问题。还有,为什么要使用完整的单词“jQuery”?兼容性问题?为什么不直接使用“$”?可能值得一提的是,如果此代码运行时图像未完全下载,则宽度和高度将返回为零,或者可能返回其他一些不正确的值。准确检测图像何时完全加载非常棘手,因为如果从缓存中提取图像,则不会触发
.load
事件。看看这个问题的解决方案。那么,到底是什么问题?我看没问题。还有,为什么要使用完整的单词“jQuery”?兼容性问题?为什么不直接使用“$”?可能值得一提的是,如果此代码运行时图像未完全下载,则宽度和高度将返回为零,或者可能返回其他一些不正确的值。准确检测图像何时完全加载非常棘手,因为如果从缓存中提取图像,则不会触发.load
事件。请参阅以获取此问题的解决方案。如果图像是jQuery对象,则这是正确的。是-v.true,我做了一些更改并添加了一个小提琴使其工作。你找错了方向。非jQuery JavaScript具有宽度和高度属性,如果在运行代码时图像已完全加载,则应在原始代码示例中检索这些属性。如果图像是jQuery对象,则为真。是-v.true,我做了一些改动,加了一把小提琴使它工作起来。你找错人了。非jQuery JavaScript具有宽度和高度属性,如果在运行代码时图像已完全加载,则应该在原始代码示例中检索这些属性。