3

我希望能够.load()在创建元素 - 图像元素时执行函数的回调。该代码通过以下代码加载新的图像元素来工作:

$('<img />').load(function()
{
    var img = this;
    $('.block-wrap img').fadeOut('slow', function()
    {
        $(this).replaceWith(img);
    });
}).attr('src', loadurl);

但是我希望在加载和替换图像后能够继续。这就是我需要它的工作方式:

$('<img />').load(function()
{
    var img = this;
    $('.block-wrap img').fadeOut('slow', function()
    {
        $(this).replaceWith(img);
    });
}).attr('src', loadurl);

$('.block-wrap input.imageheight').val($('.block-wrap img').height());
$('.block-wrap input.imagewidth').val($('.block-wrap img').width());

它返回第一个图像高度(不是已被替换的图像,它是加载微调器图像),因此我需要它能够在图像完全加载到 DOM 时检索图像的高度和宽度。太糟糕.replaceWith()了,没有回调方法,但我不能使用回调函数,.load()因为它是一个通过函数传递的函数,所以它.load()不起作用。

4

2 回答 2

0

我不是 100% 的,但你能不能在 replaceWith 的末尾添加一个加载事件?IE:

$(this).replaceWith(img).load(function(){

   $('.block-wrap input.imageheight').val($('.block-wrap img').height());
   $('.block-wrap input.imagewidth').val($('.block-wrap img').width());

});
于 2011-03-24T16:27:53.533 回答
0

它返回错误的图像尺寸,因为$('.block-wrap img').height()和在完成之前$('.block-wrap img').width()被调用。 .load()

您可以将这两行放在load回调中(在 之后.replaceWith),以便它们引用正确的图像。

$('<img />').load(function()
{
    var img = this;
    $('.block-wrap img').fadeOut('slow', function()
    {
        $(this).replaceWith(img);
        $('.block-wrap input.imageheight').val($('.block-wrap img').height());
        $('.block-wrap input.imagewidth').val($('.block-wrap img').width());
    });
}).attr('src', loadurl);
于 2011-03-24T16:48:54.083 回答