【问题标题】:determine width and height of an image while it isn't inserted to the dom确定图像未插入 dom 时的宽度和高度
【发布时间】:2013-09-10 15:37:38
【问题描述】:

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

图片的url肯定在result[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 的情况下检查图像宽度和高度的正确方法?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

试试这个:

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         
}

或查看此链接:Getting auto size of IMG before adding it to DOM (Using JQuery)

【讨论】:

    【解决方案2】:

    由于设置 jQuery("&lt;img&gt;") 的 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]);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 2014-09-18
    • 2015-07-02
    • 1970-01-01
    相关资源
    最近更新 更多