确定图像未插入 DOM 时的宽度和高度

determine width and height of an image while it isn't inserted to the dom

本文关键字:高度 DOM 图像 插入      更新时间:2023-09-26

我正在使用 ajax 调用从服务器接收长字符串中的图像

图像的网址肯定在结果[1]内。我使用了width/naturalWidth和height/naturalHeight,有时它们返回0,在其他情况下,它们返回正确的像素大小

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 的情况下检查图像宽度和高度的正确方法?

试试这个:

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         
}

或查看此链接:在将 IMG 添加到 DOM 之前获取其自动大小(使用 JQuery)

出现问题是因为设置jQuery("<img>")的 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]);