jQuery动态加载图像 [英] jquery loading images dynamically

查看:79
本文介绍了jQuery动态加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个img元素,每次动态更改其src时,我想获取新图像的宽度(完全加载后)

I have an img element and each time I change its src dynamically I want to get new image's width (after it's completely loaded)

.load()如果图像已经在缓存中(?)似乎没有触发,但是在这种情况下,我不想再次加载它,例如:

.load() seems not trigger if image is in cache already(?), but I don't want to load it again in this case, as:

   'image.jpg?' + new Date().getTime();

会(?)

最好的方法是什么?

$('#test img:first').load(function() {
    console.log($(this).width());
});

似乎它不会触发缓存中的图像

seems it doesn't trigger if images in cache already

推荐答案

.load()如果图像位于缓存中并且在设置.src属性之前未安装onload处理程序,则不会触发.在某些浏览器(IE)中显示图片.

.load() will not trigger if the image is in the cache and the onload handler is not installed on before the .src property is set on the image in some browsers (IE).

如果图像是使用javascript动态创建的,则只需确保在设置.src属性之前已分配onload处理程序即可.

If the image is being dynamically created with javascript, then just make sure that the onload handler is assigned BEFORE the .src property is set.

如果图像在页面HTML中,那么确保您获得该特定图像的onload事件的唯一方法是,如果您在HTML本身中指定了onload处理程序.无法在HTML中为图像安装带有javascript的onload处理程序,并确保调用该处理程序,因为该图像可能在运行任何javascript之前就已加载.

If the image is in the page HTML, then the only way to guarantee you get an onload event for that particular image is if you have an onload handler specified in the HTML itself. There is no way to install an onload handler with javascript for an image in your HTML and make sure that it gets called because the image may already be loaded before any javascript runs.

您可以检查.complete属性是否已加载图像.

You can check to see if an image is already loaded with the .complete property.

因此,HTML中图像的解决方法是:

So, a work-around for an image in your HTML would be this:

var img = $('#test img:first');
if (!img[0].complete) {
    img.load(function() {
        // onload code here
    });
} else {
   // image already loaded
}

这篇关于jQuery动态加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆