I have this code so far:

到目前为止我有这个代码:

var img = document.getElementById('draggable');
var width = img.clientWidth;
var height = img.clientHeight;

However this gets me the html attributes - css styles. I want to get dimensions of the actual image resource, of the file.

然而,这让我获得了html属性--css样式。我想获得文件的实际图像资源的维度。

I need this because upon uploading an image, it's width gets set to 0px and I have no idea why or where this is happening. To prevent it I want to get the actual dimension and reset them. Is this possible?

我需要这个,因为在上传图像时,它的宽度设置为0px,我不知道为什么或在哪里发生这种情况。为了防止它,我想获得实际尺寸并重置它们。这可能吗?

Edit: Even when I try to get naturalWidth I get 0 as a result. I've added a picture. The weird thing is that it only happens when I upload new files and upon refresh it's working as it should.

编辑:即使我尝试获得naturalWidth,我也会得到0。我添加了一张图片。奇怪的是,只有当我上传新文件并刷新它才能正常工作时才会发生这种情况。

http://oi39.tinypic.com/3582xq9.jpg

http://oi39.tinypic.com/3582xq9.jpg

3 个解决方案

#1


36

You could use naturalWidth and naturalHeight, these properties contain the actual, non-modified width and height of the image, but you have to wait until the image has loaded to get them

您可以使用naturalWidth和naturalHeight,这些属性包含图像的实际未修改宽度和高度,但您必须等到图像加载后才能获取它们

var img = document.getElementById('draggable');

img.onload = function() {
    var width  = img.naturalWidth;
    var height = img.naturalHeight;
}

This is only supported from IE9 and up, if you have to support older browser you could create a new image, set it's source to the same image, and if you don't modify the size of the image, it will return the images natural size, as that would be the default when no other size is given

这仅支持从IE9及以上,如果您必须支持旧浏览器,您可以创建一个新图像,将它的源设置为相同的图像,如果您不修改图像的大小,它将返回图像自然大小,因为没有给出其他大小时将是默认值

var img     = document.getElementById('draggable'),
    new_img = new Image();

new_img.onload = function() {
    var width  = this.width,
        heigth = this.height;
}

new_img.src = img.src;

FIDDLE

小提琴

更多相关文章

  1. 如何在流体宽度旋转木马中的页面之间创建装订线?
  2. 通过AJAX加载内容和预加载图像?
  3. 获取背景图像的最终大小
  4. 如何将加载微调器图像添加到jquery选项卡中的每个选项卡?
  5. jQuery的宽度、内宽和外宽、高度、内高和外高有什么区别
  6. 在执行ajax时显示加载图像
  7. 当AJAX响应来自PHP文件时,如何显示以消息为中心的加载器图像&防止
  8. 文字效果 - 图像到css / jQuery
  9. 模态的jQuery动态高度宽度

随机推荐

  1. Android NDK 学习之传递类对象
  2. Android Studio升级后projectBuild faile
  3. Android中的EditText属性说明
  4. 在Android(安卓)Studio中自定义字体库报
  5. Android弹幕实现:基于B站弹幕开源系统(2)
  6. android 中文API:android
  7. Android之使用Android-query框架开发实战
  8. 2016年3月1日Android实习笔记
  9. android抽屉效果
  10. Android中ImageView和VideoView铺满父元