在 javascript/jquery 中获取完整大小的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9631803/
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
Get full size of image in javascript/jquery
提问by emc
I have an image on page that has been resized to fit in a div, say, 400x300. How can I get the full size of the image (~4000x3000) in jQuery? .width() and .height() only seem to return the current size of the image.
我在页面上有一个图像,该图像已调整大小以适合 div,例如 400x300。如何在 jQuery 中获得图像的完整尺寸(~4000x3000)?.width() 和 .height() 似乎只返回图像的当前大小。
回答by adeneo
Images have naturalWidth
and naturalHeight
properties that contain the actual, non-modified width and height of the image, i.e. the real dimensions of the image, not what CSS sets it to.
图片有naturalWidth
和naturalHeight
包含实际的,未经修饰的宽度和图像的高度,即图像的实际尺寸,不是CSS设置它的属性。
One would still have to wait for the image to load though
虽然仍然需要等待图像加载
$('#idOfMyimg').on('load', function() {
var height = this.naturalHeight,
width = this.naturalWidth;
});
Another option would be to create a new image with the same file as the source, and get the dimensions from that, as long as it's never added to the DOM, not external styles will affect it
另一种选择是使用与源文件相同的文件创建一个新图像,并从中获取尺寸,只要它从未添加到 DOM 中,外部样式不会影响它
var img = new Image();
img.onload = function() {
var height = this.height,
width = this.width;
}
img.src = $('#idOfMyimg').attr('src');
回答by GregL
You can clone the image, remove the height and width attributes, append it to the body and get the width and size before removing it.
您可以克隆图像,删除高度和宽度属性,将其附加到正文并在删除之前获取宽度和大小。
jsFiddle demo is here: http://jsfiddle.net/58dA2/
jsFiddle 演示在这里:http: //jsfiddle.net/58dA2/
Code is:
代码是:
$(function() {
var img = $('#kitteh'); // image selector
var hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
$('#height').text(hiddenImg.height());
$('#width').text(hiddenImg.width());
hiddenImg.remove();
});?
回答by m90
You can do this with an Image
object that holds the same source file like:
您可以使用Image
包含相同源文件的对象来执行此操作,例如:
var preloader = new Image();
preloader.src = 'path/to/my/file.jpg';
preloader.onload = function(){
var height = preloader.height;
var width = preloader.width;
}
回答by Java
Try this:
试试这个:
var pic = $("img")
var pic = $("img")
// need to remove these in of case img-element has set width and height pic.removeAttr("width"); pic.removeAttr("height");
// 如果 img-element 设置了宽度和高度,则需要删除这些 pic.removeAttr("width"); pic.removeAttr("高度");
var pic_real_width = pic.width(); var pic_real_height = pic.height();
var pic_real_width = pic.width(); var pic_real_height = pic.height();