我的图片会在用户点击其他缩略图时发生变化。
如何让它可靠地获取即将加载的图像的尺寸?
目前我有:
$('#mainImg').animate({opacity: 0.01}, 500, function() {
$('#mainImg').attr('src', '/cakes/' + file);
setTimeout(function() {
center('#mainImg');
$('#mainImg').animate({opacity: 1.00}, 500);
}, 100)
})
这是一个比我以前更可靠的解决方法:
$('#mainImg').fadeOut('fast', function(){
$('#mainImg').attr('src', '/cakes/'+file);
center('#mainImg');
$('#mainImg').fadeIn('fast');
})
功能中心现在只是:
function center(imageElement)
{
var ph = $(imageElement).parent().height();
var pw = $(imageElement).parent().width();
var ih = $(imageElement).height();
var iw = $(imageElement).width();
alert(iw)
}
答案 0 :(得分:1)
您应首先预先加载图像以获得可靠的尺寸。尝试这样的事情:
$('#mainImg').animate({opacity: 0.01}, 500, function() {
var $this = $(this),
src = '/cakes/' + file;
preloadImage(src, function() {
$this.attr('src', src);
center($this);
$this.animate({opacity: 1.00}, 500);
});
});
preloadImage(src, callback) {
var img = new Image();
img.onload = callback;
img.src = src;
}
同时修改center
函数以使用已有的缓存变量:
function center($imageElement) {
var ih = $imageElement[0].height;
var iw = $imageElement[0].width;
alert(iw)
}
答案 1 :(得分:0)
我认为您必须预先加载该图片,如下所示:
var image = new Image();
image.src = "https://www.google.nl/images/srpr/logo11w.png";
image.onload = function () {
// Do whatever you want with this.width and this.height overhere.
console.log(this.width);
console.log(this.height);
}
答案 2 :(得分:0)
与已发布的答案类似,但对于不正确支持图片加载事件的浏览器的回退:
$('#mainImg').animate({opacity: 0.01}, 500, function() {
// run the load event only once
$('#mainImg').one('load', function() {
// do whatever you want to do if image is loaded...
console.log(this.width);
console.log(this.height);
})
.attr('src', '/cakes/' + file);
.each(function() {
//Cache fix for browsers that don't trigger .load()
if(this.complete) $(this).trigger('load');
});
})