Javascript jQuery代码使用图像源查找图像的宽度和高度
在我们的网站中,我们正在访问我们的图像或图像源Javascript jQuery代码使用图像源查找图像的宽度和高度,javascript,jquery,image,Javascript,Jquery,Image,在我们的网站中,我们正在访问我们的图像或图像源 <img src="image_manage.php&type=resize&id=12" /> 但是我得到的高度和宽度的值都是零。问题是什么?试试下面的代码: var oImage = new Image(); oImage.onload = function(){ this.width// width of loaded image } oImage.src = '/path/to/image.gif'
<img src="image_manage.php&type=resize&id=12" />
但是我得到的高度和宽度的值都是零。问题是什么?试试下面的代码:
var oImage = new Image();
oImage.onload = function(){
this.width// width of loaded image
}
oImage.src = '/path/to/image.gif';
或者类似的更好:
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
试试这个
width = $("img").attr('width'); //can also $("img").width();
hight = $("img").attr('height'); //can also $("img").height();
您必须等待图像加载才能检测其大小
$("#imgElement").attr('src',photograf.src).load(function(){
var w = $("imgElement").width();
var h = $("imgElement").height();
});
这里我设置图像的src
参数,并使用jQuery的load()
函数检测图像何时成功加载
参考-
jQuery(function(){
var $width = jQuery("img").width();
var $height = jQuery("img").height();
});
你可以试试这个
width = $("img").prop('width');
hight = $("img").prop('height');
不要忘记将js代码放入load
或documentready
事件中
$(document).ready(function(){
var height = $('img').prop('height');
var width= $('img').prop('width');
alert('Height :'+height+' AND '+'width :'+width);
});
下面是一个运行示例
示例
当您询问图像大小时,图像尚未加载。onLoad方法对此很有帮助
photograf = new Image();
photograf.src = '/image_manage.php&type=resize&id=12';
photograf.onLoad = function(){
var width = this.width;
var height = this.height;
};
重复:
photograf = new Image();
photograf.src = '/image_manage.php&type=resize&id=12';
photograf.onLoad = function(){
var width = this.width;
var height = this.height;
};