如何使用jQuery加载图片?

4

我正在做的是加载图像并在对话框中显示图像。

<div id="image_preview" title="Client Photo Preview">
   <p><img src="" alt="client image" id="client_image_preview" /></p>
</div>

$("#client_image_preview").attr("src", imagelocation);

$('#image_preview').dialog({
    height: 'auto',
    width: 'auto',
    modal: true,
    dialogClass: 'titleless',
    buttons: { "CLOSE": function() { $(this).dialog("destroy"); } }
});

有没有办法在使用jQuery加载图片时显示加载动画?
谢谢。
1个回答

9

在您的img标签中设置一个初始的加载gif图像。然后使用JavaScript Image对象和onload事件预加载图像;当目标图像完成预加载时,将您的img标签的src替换为其URI。

<div id="image_preview" title="Client Photo Preview">
   <p><img src="loading.gif" alt="client image" id="client_image_preview" /></p>
</div>

var img = new Image();
img.onload = function() {
    $("#client_image_preview").attr("src", imagelocation);
}
img.src = imagelocation;

$('#image_preview').dialog({
    height: 'auto',
    width: 'auto',
    modal: true,
    dialogClass: 'titleless',
    buttons: { "CLOSE": function() { $(this).dialog("destroy"); } }
});

你好 @joshperry,我想现在释放img资源...将其分配为null就足够了吗? - alexserver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接