我正在创建一个jQuery插件。
我如何得到真实的图像宽度和高度与Javascript在Safari?
Firefox 3、IE7和Opera 9的操作如下:
var pic = $("img")
// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real_width = pic.width();
var pic_real_height = pic.height();
但在Safari和谷歌等Webkit浏览器中,Chrome的值为0。
My situation is probably a little different. I am dynamically changing the src of an image via javascript and needed to ensure that the new image is sized proportionally to fit a fixed container (in a photo gallery). I initially just removed the width and height attributes of the image after it is loaded (via the image's load event) and reset these after calculating the preferred dimensions. However, that does not work in Safari and possibly IE (I have not tested it in IE thoroughly, but the image doesn't even show, so...).
Safari保留了前一张图片的尺寸所以尺寸总是在后面一张图片上。我认为这和缓存有关。因此,最简单的解决方案是克隆图像并将其添加到DOM中(重要的是将其添加到DOM中以获得with和height)。给图像一个可见值为hidden(不要使用display none,因为它不起作用)。获得尺寸后,删除克隆。
下面是我使用jQuery的代码:
// Hack for Safari and others
// clone the image and add it to the DOM
// to get the actual width and height
// of the newly loaded image
var cloned,
o_width,
o_height,
src = 'my_image.jpg',
img = [some existing image object];
$(img)
.load(function()
{
$(this).removeAttr('height').removeAttr('width');
cloned = $(this).clone().css({visibility:'hidden'});
$('body').append(cloned);
o_width = cloned.get(0).width; // I prefer to use native javascript for this
o_height = cloned.get(0).height; // I prefer to use native javascript for this
cloned.remove();
$(this).attr({width:o_width, height:o_height});
})
.attr(src:src);
这个解决方案在任何情况下都有效。
我已经做了一些变通的实用函数,使用imagesLoaded jquery插件:
https://github.com/desandro/imagesloaded
function waitForImageSize(src, func, ctx){
if(!ctx)ctx = window;
var img = new Image();
img.src = src;
$(img).imagesLoaded($.proxy(function(){
var w = this.img.innerWidth||this.img.naturalWidth;
var h = this.img.innerHeight||this.img.naturalHeight;
this.func.call(this.ctx, w, h, this.img);
},{img: img, func: func, ctx: ctx}));
},
你可以通过传递url,函数和它的上下文来使用它。函数在图像加载后执行,并返回创建的图像及其宽度和高度。
waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)
关于从WebKit缓存加载图像时onload事件不会触发的问题,在已接受的回答中有很多讨论。
在我的例子中,onload触发了缓存图像,但高度和宽度仍然为0。一个简单的setTimeout解决了我的问题:
$("img").one("load", function(){
var img = this;
setTimeout(function(){
// do something based on img.width and/or img.height
}, 0);
});
我不能说为什么onload事件即使从缓存加载图像时也会触发(改进了jQuery 1.4/1.5?) -但如果你仍然遇到这个问题,可能是我的答案和var src = img.src;img。SRC = "";img。SRC = SRC;技巧是有用的。
(请注意,就我的目的而言,我不关心图像属性或CSS样式中的预定义维度——但根据Xavi的回答,您可能想要删除这些维度。或者克隆图像。)