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

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

    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();
    

提交回复
热议问题