我正试图在jQuery中实现类似于照片轮播的内容。这个轮播可以使用一系列图像来源填充图像(我发出一个ajax请求,返回带有这些数据的json),一旦填充完成,您可以调用几个方法,previous()和next()来移动传送带分别向后和向前。在运行中创建jQuery元素时是否触发了“就绪”事件?
事情是这个功能已经实现并正在工作,但我不能解决调整过程中的一个问题。为了避免图像超出容器边界,我有一个方法来创建和调整图像的大小,如果需要的话。
this.getImageResized = function(imageSrc) {
var image = $('<img />', {src : imageSrc});
// Container ratio
var ratio = this.itemMaxWidth/this.itemMaxHeight;
// Target image ratio is WIDER than container ratio
if((image[0].width/image[0].height) > ratio) {
if(image[0].width > this.itemMaxWidth) {
image.css('width', this.itemMaxWidth + 'px');
image.css('height', 'auto');
}
// HIGHER
} else {
if(image[0].height > this.itemMaxHeight) {
image.css('width', 'auto');
image.css('height', this.itemMaxHeight + 'px');
}
}
// Embeds image into a wrapper with item's width and height
var wrapper = $('<span style="display : block; float : left; width : ' + this.itemMaxWidth + 'px; height : ' + this.itemMaxHeight + 'px"></span>');
image.appendTo(wrapper);
return wrapper;
};
测试此功能,我发现有时,图像没有按预期调整大小。我已经使用firebug console.log()在jQuery元素创建之下记录图像[0] .width,发现有时值为0.
我不是jQuery的专家,但我想当发生这种情况(值为0)是因为元素没有准备好。
如何确保当我询问其宽度和高度值时,元素已经加载?
是这样的可能吗?
var image = $('<img />', {src : imageSrc}).ready(function() {
// But image[0].width it's not available here!
});
谢谢你的帮忙!
可能重复的[图片加载jQuery事件](http://stackoverflow.com/questions/910727/jquery-event-for-images-loaded) – spender 2010-06-22 21:42:14
@spender - 请参阅我对Sarfraz的答案的评论...这不是'同样的问题,这也不是合适的答案,这不应该作为一个重复被关闭......因为,瓦特呃,这是一个不同的问题。 – 2010-06-22 21:50:44
@Nick,我只能认为你没有发现Sarfaz正在使用窗口加载事件,但链接问题中的答案使用图像加载事件。我会发布一个答案来演示,但它确实不是必要的。 – spender 2010-06-22 22:51:02