Is there any way to read out the “naturalWidth” of an image with jquery?

前端 未结 8 2159
时光说笑
时光说笑 2020-12-05 10:59

I tried with something like this:

var Height = $(this).naturalHeight;

But it doesn\'t work. Is there any way to do that

greez

8条回答
  •  孤街浪徒
    2020-12-05 11:11

    Here is an example of a jQuery function which works on older IE versions even for large images.

    /*
     * NaturalWith calculation function. It has to be async, because sometimes(e.g. for IE) it needs to wait for already cached image to load.
     * @param onNaturalWidthDefined callback(img) to be notified when naturalWidth is determined.
     */
    jQuery.fn.calculateNaturalWidth = function(onNaturalWidthDefined) {
        var img = this[0];
        var naturalWidth = img.naturalWidth;
        if (naturalWidth) {
            onNaturalWidthDefined(img);
        } else { //No naturalWidth attribute in IE<9 - calculate it manually.
            var newImg = new Image();
            newImg.src = img.src;
            //Wait for image to load
            if (newImg.complete) {
                img.naturalWidth = newImg.width;
                onNaturalWidthDefined(img);
            } else {
                $(newImg).load(function() {img.naturalWidth=newImg.width; onNaturalWidthDefined(img)});
            }
        }
    };
    

    Usage is simple:

    $(img).calculateNaturalWidth(function(img) { alert(img.naturalWidth)});
    

提交回复
热议问题