get uploaded image dimensions with javascript / jquery?

亡梦爱人 提交于 2019-12-13 03:09:17

问题


also try this but for me it isnt working.

Determining image file size + dimensions via Javascript?

i upload image, insert it on page through jquery and want to create div around inserted image, but dont know image dimensions.

$("#temp_image").html('<img src="uploads/obr1.jpg" alt="" id="tmp" />');
var img = document.getElementById('temp_image');
alert(img.clientWidth);

it show me 0, what is wrong ?

also tried:

var oImg = new Image();
oImg.src = 'uploads/obr1.jpg;
if (oImg.complete) {
  alert(oImg.width)
} 

it shows me 0 too.

where is problem ? thanks


回答1:


Should be:

$("#temp_image").html('<img src="uploads/obr1.jpg" alt="" id="tmp" />');
var img = document.getElementById('tmp');
alert(img.clientWidth);

You are currently trying to get the width of the containing div (#temp_image), not the image.

Also, if you are using jQuery, you can just do:

$("#temp_image").html('<img src="uploads/obr1.jpg" alt="" id="tmp" />');
alert($('#tmp').width());

Hope this helps!




回答2:


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

doesn't actually get you the image element, it gets the element containing the image. You should try

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

or

var img = $('#tmp')[0];

instead. Also make sure that the image is actually visible when you're getting it's dimensions, as clientWidth and clientHeight will be zero if the element is hidden.




回答3:


I tried your method and it's working. You just didn't wrote it well. You forgot to close quotes.

var oImg = new Image();
oImg.src = 'uploads/obr1.jpg';
if (oImg.complete) {
  alert(oImg.width)
}


来源:https://stackoverflow.com/questions/1491199/get-uploaded-image-dimensions-with-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!