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

前端 未结 8 2133
时光说笑
时光说笑 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:05

    The best you can do is to hide an image without setting the width and height and use the image source for this image as your original image. Then calculate the dimension of this hidden image.

    Or else you can calculate the physical dimension in server side and pass that to a hidden element in the page and fetch the size from that hidden element value.

    0 讨论(0)
  • 2020-12-05 11:05

    Source From HERE

    Here is a short jQuery (any version) plugin that adds two methods: naturalWidth() and naturalHeight(). It uses branching to determine if naturalWidth and naturalHeight are supported by the browser. If supported, the method just becomes a getter for the naturalWidth or naturalHeight property. If not supported, the method creates a new unstyled image element and returns that element's actual width and height.

      // adds .naturalWidth() and .naturalHeight() methods to jQuery
      // for retreaving a normalized naturalWidth and naturalHeight.
      (function($){
        var
        props = ['Width', 'Height'],
        prop;
    
        while (prop = props.pop()) {
        (function (natural, prop) {
          $.fn[natural] = (natural in new Image()) ? 
          function () {
          return this[0][natural];
          } : 
          function () {
          var 
          node = this[0],
          img,
          value;
    
          if (node.tagName.toLowerCase() === 'img') {
            img = new Image();
            img.src = node.src,
            value = img[prop];
          }
          return value;
          };
        }('natural' + prop, prop.toLowerCase()));
        }
      }(jQuery));
    
      // Example usage:
      var 
      nWidth = $('img#example').naturalWidth(),
      nHeight = $('img#example').naturalHeight();
    
    0 讨论(0)
  • 2020-12-05 11:07

    Would just try

    var width = $("img", this).css('width', 'auto').width();
    var height= $("img", this).css('height', 'auto').height();
    

    Is basically the calculation for naturalWidth and naturalHeight anyway

    0 讨论(0)
  • 2020-12-05 11:08

    It looks to me like the accepted solution modifies the appearance of the object. Occasionally jQuery is a little too helpful and you have to tell it to get out of your way. If you want to use naturalWidth or naturalHeight then just use the one that already exists by converting the jQuery object into a native browser element reference.

    var Height = document.getElementById($(this).attr("id")).naturalHeight;
    
    0 讨论(0)
  • 2020-12-05 11:08

    One way to get the dimensions of an image is to dynamically load a copy of the image using javascript and obtain it's dimensions:

    // preload the image
    var height, width = '';
    var img = new Image();
    var imgSrc = '/path/to/image.jpg';
    
    $(img).load(function () {
        alert('height: ' + img.height);
        alert('width: ' + img.width);
        // garbage collect img
        delete img;
    }).error(function () {
        // image couldnt be loaded
        alert('An error occurred and your image could not be loaded.  Please try again.');
    }).attr({ src: imgSrc });
    
    0 讨论(0)
  • 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)});
    
    0 讨论(0)
提交回复
热议问题