问题描述
我正在使用JQuery动态地将IMG组件添加到我的DOM中,但是根据它们的大小,我将以不同的方式添加它们。在将DOM添加到DOM之前,任何人都有一个好主意来获取IMG的自动调整尺寸?注意:我正在使用DOM代码段JQuery操作,如,但是img维度为= 0。
您可以在不将图像附加到DOM的情况下执行此操作。 Kristoffer(嘿,这也是我的名字!)在正确的轨道上,但是图像需要加载才能尝试阅读宽度/高度。
var getImageSize = function(src){
var img = new Image();
$(img).bind('load',function(e){
var height = img.height;
var width = img.width;
document.write 'width:'+ width +',height:'+ height);
});
img.src = src;
};
getImageSize('http://farm4.static.flickr.com/3261/5791911248_b777cb1dde_b.jpg');
演示此处:
I'm dynamically adding IMG components to my DOM using JQuery, but depending on how big they are, I'll be adding them in different ways. Anyone have a good idea for getting the IMG's auto sized dimensions BEFORE I add it to the DOM?
NOTE: I was playing around with DOM snippet JQuery manipulation, as described here, but the img dimensions were = 0.
You should be able to do this without appending the image to the DOM. Kristoffer (hey that's my name too!) is on the right track but the image needs to be loaded before you can try to read the width / height.
var getImageSize = function(src) {
var img = new Image();
$(img).bind('load', function(e) {
var height = img.height;
var width = img.width;
document.write('width:' + width + ', height: ' + height);
});
img.src = src;
};
getImageSize('http://farm4.static.flickr.com/3261/5791911248_b777cb1dde_b.jpg');
Demo here: http://jsfiddle.net/H3p97/
这篇关于将IMG的自动大小添加到DOM之前(使用JQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!