同步多个jQuery属性更新

时间:2011-12-26 19:33:15

标签: javascript jquery

我在使用jQuery动态更新图像元素的一些例程时遇到了一些麻烦。一个示例是替换大图像的脚本,调整过程中的维度。

$('#image').attr('src',path);
$('#image').attr('width',width);
$('#image').attr('height',height);

执行此操作时,我看到屏幕上的图像失真(放置新图像并更改尺寸),然后我的图像正确显示。

我尝试添加.hide()和.show()标签来掩盖更改,但我得到了相同的结果。

$('#image').hide();
$('#image').attr('src',path);
$('#image').attr('width',width);
$('#image').show();
$('#image').attr('height',height);

是否有某种缓冲技术可以避免这些问题?

2 个答案:

答案 0 :(得分:1)

尝试将所有属性合并到一个调用中:

$('#image').attr({
    'src'    : path,
    'width'  : width,
    'height' : height
});

编辑:另外,如果您手头没有图像尺寸,请考虑预加载大图像。

答案 1 :(得分:1)

要在通过更新src属性替换之前预先加载图片,您可以使用以下某些Javascript:

var preload_image = new Image();

preload_image.onload = function()
{
    $('#image').attr('src', path);
    $('#image').attr('width', preload_image.width);
    $('#image').attr('height', preload_image.height);
};

preload_image.src = path;

不幸的是,据我所知,jQuery没有一组特定的功能来预加载图像......!希望这可以帮助! :)