Javascript 确定图像未插入dom时的宽度和高度
我使用ajax调用从服务器接收长字符串中的图像 图像的url肯定在结果[1]中。 我使用了width/naturalWidth和height/naturalHeight,有时它们返回0,在其他情况下,它们返回正确的像素大小Javascript 确定图像未插入dom时的宽度和高度,javascript,jquery,Javascript,Jquery,我使用ajax调用从服务器接收长字符串中的图像 图像的url肯定在结果[1]中。 我使用了width/naturalWidth和height/naturalHeight,有时它们返回0,在其他情况下,它们返回正确的像素大小 var imgElement = jQuery("<img>").attr("src", result[1]); var width = imgElement[0].naturalWidth; var height = imgElement[0].naturalH
var imgElement = jQuery("<img>").attr("src", result[1]);
var width = imgElement[0].naturalWidth;
var height = imgElement[0].naturalHeight;
if (width >= that.minImgPixels && height >= that.minImgPixels) {
image = result[1];
}
在不将图像插入dom的情况下检查图像宽度和高度的正确方法是什么?问题发生在设置JQueryTake时间的src时,javascript继续运行到下一行,该行生成0,因为图像尚未加载 解决方案是设置如下加载事件: 试试这个:
var imgElement = jQuery("<img>").load(function(){
var width = imgElement[0].naturalWidth;
var height = imgElement[0].naturalHeight;
if (width >= that.minImgPixels && height >= that.minImgPixels) {
image = result[1];
}
}).attr("src", result[1]);
或者,请参阅此链接:请参阅此处的load method caveats对类似问题的回答,该问题向您展示了如何在javascript中以编程方式创建图像,而不必首先将其放入dom中:
function GetAnImage(src) {
var newImg = document.createElement('img');
newImg.src = src;
return newImg;
}
var newImg = GetAnImage("abc.jpg");
newImg.onload = function () {
var height = this.height;
var width = this.width;
//do with the image as you want
}