jQuery 有没有办法用jquery读出图像的“naturalWidth”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1832907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:14:02  来源:igfitidea点击:

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

jquery

提问by ValiL

I tried with something like this:

我试过这样的事情:

var Height = $(this).naturalHeight;

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

但它不起作用。有没有办法做到这一点

greez

格瑞兹

采纳答案by ctrlShiftBryan

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

回答by Ruwen

I use the native javascript properties after applying jQuery and then stripping jQuery

我在应用 jQuery 然后剥离 jQuery 后使用本机 javascript 属性

.naturalWidth / .naturalHeight

.naturalWidth / .naturalHeight

On a jQuery object i use

在我使用的 jQuery 对象上

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

or

或者

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

if no jQuery object is selected.

如果没有选择 jQuery 对象。

With get(0) on a jQuery object you can access the associated DOM-element. On the native DOM element you can work with native javascript code (here access the nativ javascript attribute .naturalWidth)

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

回答by Geordie Korper

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.

在我看来,接受的解决方案会修改对象的外观。有时 jQuery 有点太有用了,你必须告诉它让开。如果您想使用 naturalWidth 或 naturalHeight ,那么只需通过将 jQuery 对象转换为本机浏览器元素引用来使用已经存在的那个。

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

回答by Corey Ballou

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:

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

// 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 });

回答by ejboy

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

这是一个 jQuery 函数的例子,它适用于旧的 IE 版本,即使是大图像。

/*
 * 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)});

回答by Syed

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.

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

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

回答by Tim

Would just try

会尝试

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

Is basically the calculation for naturalWidthand naturalHeightanyway

基本上是计算naturalWidthnaturalHeight反正

回答by rahul

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.

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