![](/img/trans.png)
[英]How to get in JavaScript width and height of image, before it's loaded?
[英]How to get the downloaded image's width&height?
下载图像后,我想设置<img>
容器的<div>
的宽度和高度,该怎么做?
将其放在隐藏的页面上,然后测量其宽度。 请参阅此处以获取有关如何测量隐藏对象宽度的详细说明(只需调用width()返回0)。
function fn (div, url_path) {
var img = new Image();
img.onload = function () {
div.style.width = img.width;
div.style.height = img.height;
};
img.src = "url_path";
}
fn(document.getElementsByTagName('div')[0], 'http://some-url-to-image.com/1.jpg');
除非您想要错误的结果,否则最好等待图像加载。
jQuery('#image').load(function() {
var jThis = jQuery(this);
var width = jThis.width();
var height = jThis.height();
yourFunction(width, height); //whatever you want to do with these values
jThis.unbind('load'); //might be necessary if you only want this to happen once. Remove this if #image is a container for multiple uses.
})
代替yourFunction()
,您可以使用它,因为它更适合您的描述:
jThis.parents('#container').css({
width: width,
height: height
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.