我在使用 jQuery 和正在构建的自定义照片库时遇到了很多问题。我到处搜索并尝试了无数种不同的解决方案,但没有一个是完美的。那么让我介绍一下信息:
此照片库左侧有缩略图,中间有大图。可以单击每个缩略图,这会调用传递其 ID 的函数。我想要它做的是,AJAX POST 到服务器以获取图像评论和图像名称。淡出当前大图div,切换img标签中的src,获取新图片的宽度,设置叠加评论div的宽度,淡入大图div。
问题是我无法在加载新图像后获取新图像的宽度(即使使用 .load() 的形式等待图像完成加载)。现在,当我淡入新图像然后获取宽度时,我可以让它工作,但这不是我需要的。我需要在淡入之前获取宽度并设置 div 的宽度。
任何想法或更正都会很棒,希望我提供了足够的信息。
这是我正在研究的代码:
function thumbClick(val) {
$.post('ajax.php', {
photo_in: val
}, function (data) {
$('div#picture').fadeOut('slow', function () {
//$('img#big-picture').load(function(){
$('img#big-picture').one('load', function () {
//alert($('img#big-picture').width());
//will alert 0
$('div#picture').fadeIn('slow', function () {
$('div#comment-box').width($('img#big-picture').width());
//set comment to what I want
$('p#comment').html("");
//alert($('img#big-picture').width());
//will alert new image width after FadeIN
$('p#comment').html(data.comment);
});
}); //end of one(load)
$('img#big-picture').attr("src", data.newImage);
}); //end of fadeout
}, "json"); //end of post
}
最佳答案
我以前遇到过这个;似乎最简单的解决方案是快速显示图像,捕获它的宽度,然后再次隐藏它。此操作发生得如此之快,用户永远不会注意到。 在你的情况下,我相信代码是:
$("#big-picture").show();
alert($('#big-picture').width()); //this should be the real width, now
$("#big-picture").hide();
关于javascript - jQuery 在 src 更改之后和 fadeIn 之前获取 img 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6208021/