有什么办法可以通过jquery读取图像的“ naturalWidth”?

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

我尝试过这样的事情:

1
var Height = $(this).naturalHeight;

但这是行不通的。 有什么办法吗

格莱斯


在应用jQuery然后剥离jQuery之后,我使用了本地javascript属性

.naturalWidth / .naturalHeight

在我使用的jQuery对象上

1
2
var width = this.naturalWidth;
var height = this.naturalHeight;

要么

1
2
var width = $("selector").get(0).naturalWidth;
var height = $("selector").get(0).naturalHeight;

如果未选择jQuery对象。

在jQuery对象上使用get(0)可以访问关联的DOM元素。在本机DOM元素上,您可以使用本机javascript代码(在此处访问nativ javascript属性.naturalWidth)


在我看来,已接受的解决方案可以修改对象的外观。有时候jQuery有点有用,您必须告诉它摆脱困境。如果要使用naturalWidth或naturalHeight,则只需通过将jQuery对象转换为本机浏览器元素引用来使用已存在的那个。

1
var Height = document.getElementById($(this).attr("id")).naturalHeight;


获取图像尺寸的一种方法是使用javascript动态加载图像的副本并获取其尺寸:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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 });

这是一个jQuery函数的示例,即使在较大的图像上也可以在较旧的IE版本上使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * 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)});
        }
    }
};

用法很简单:

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


来源从这里

这是一个简短的jQuery(任何版本)插件,其中添加了两个方法:naturalWidth()和naturalHeight()。它使用分支来确定浏览器是否支持naturalWidth和naturalHeight。如果支持,该方法将成为naturalWidth或naturalHeight属性的吸气剂。如果不支持,该方法将创建一个新的未样式化图像元素,并返回该元素的实际宽度和高度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  // 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();

会尝试

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

基本上是naturalWidthnaturalHeight的计算


最好的办法是隐藏图像而不设置宽度和高度,并将该图像的图像源用作原始图像。然后计算该隐藏图像的尺寸。

否则,您可以在服务器端计算物理尺寸,并将其传递给页面中的隐藏元素,然后从该隐藏元素值中获取大小。


1
2
$this.css('height', 'auto');
var height = $this.height();