捕获图像的加载事件以动态更改其来源 [英] Capturing load event for images dynamically changing their source

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

问题描述

我正在动态更改图像的src,并希望捕获该图像的加载事件.有办法吗?

I am changing src for image dynamically and want to capture on load event for that image. Is there a way I can do it?

推荐答案

几年前,我发现在第二次设置.src时,在某些浏览器(我不记得是哪个浏览器)中,onload事件并不可靠.时间.因此,我决定更换图像对象.我将创建一个新的图像对象,设置onload处理程序,设置.src值,然后在加载时将其插入到页面中,以代替现有图像.

Several years ago, I discovered that the onload event was not reliable in some browsers (I don't remember which ones) when setting .src for the second time. As such, I settled for replacing the image object. I would create a new image object, set the onload handler, set the .src value and then when it loads, insert it into the page in place of the existing image.

使用javascript从头开始创建图像时,您可以执行以下操作:

When creating an image from scratch in javascript, you do this:

var img = new Image();
img.onload = function() {
    // put your onload code here
};
img.src = "xxx.jpg"

如果只想更改图像的.src,则只需在页面中找到DOM对象并将其设置为.src属性即可.

If you just want to change the .src of an image, you just find the DOM object in the page and set it's .src property.

var img = document.getElementById("myImage");
img.src = "xxx.jpg";

如果您想在重置.src时尝试捕获onload事件(几年前我遇到可靠性问题,您可以这样做:

If you want to try to capture the onload event when resetting the .src (what I had reliability problems with a couple years ago, you would do this:

var img = document.getElementById("myImage");
img.onload = function() {
    // your code here
};
img.src = "xxx.jpg";

如果要加载新图像并在加载时替换现有图像,则可以执行以下操作:

If you want to load a new image and replace an existing one with it when it loads, you would do this:

function replaceImg(oldImage, newSrc) {
    var img = new Image();
    img.onload = function() {
        var parent = oldImage.parentNode;
        parent.insertBefore(img, oldImage);
        parent.removeChild(oldImage);
        // put any other code you want here when the 
        // replacement image is loaded and in place
    };
    img.src = newSrc;
}

而且,您可以这样称呼它:

And, you would call this like this:

<img id="myImage" src="yyy.jpg">


var oldImage = document.getElementById("myImage");
replaceImg(oldImage, "xxx.jpg");

这篇关于捕获图像的加载事件以动态更改其来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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