Javascript图像onload [英] Javascript image onload

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

问题描述

我正在尝试在加载先前加载的图像时加载新图像。
函数create_photo_list正常工作。它创建一组需要加载的照片。如果不需要加载,那么数组是空的。问题是,当没有更多的项目加载它不断调用load_next_photo函数。

I am trying to load a new image every time the previously loaded image has finished loading. The function create_photo_list works correctly. It creates an array of the photos that need to be loaded. If none need to be loaded then the array is empty. The problem is, when there are no more items to load the it keeps calling the load_next_photo function.

我在函数中每次调用registerEventHandler的原因是因为如果我不要,当下一张照片加载时,该函数不被调用。

The reason I call the registerEventHandler every time in the function is because if I don't, the function is not called when the next photo loads.

    function registerEventHandler(node, event, handler) {
    if (typeof node.addEventListener == "function")
        node.addEventListener(event, handler, false);
    else
        node.attachEvent("on" + event, handler);
}

// Remove an HTML element event handler such as onclick
// ex: unregisterEventHandler($("textfield"), "keypress", showEvent);
function unregisterEventHandler(node, event, handler) {
if (typeof node.removeEventListener == "function")
    node.removeEventListener(event, handler, false);
else
    node.detachEvent("on" + event, handler);
}

function load_next_photo() {
    var loading_list = create_photo_list();
    alert(loading_list.length);
    if (loading_list.length > 0) {
        img[loading_list[0]]['loaded'] = 1;
        registerEventHandler($("load_img"), "onload", load_next_photo());
        $("load_img").src = img[loading_list[0]]['img'];
    }
    else {
        alert("nothing");
        unregisterEventHandler($("load_img"), "onload", load_next_photo())
    }
    unregisterEventHandler($("load_img"), "onload", load_next_photo())
}


推荐答案

目前已经有这样的代码,但这样的代码工作正常:

Can't get my head around what you currently have, but such code works just fine:

var _images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var _index = 0;

window.onload = function() {
    LoadImage();
};

function LoadImage() {
    //stop condition:
    if (_index >= _images.length)
        return false;

    var url = _images[_index];
    var img = new Image();
    img.src = url;
    img.onload = function() {
        _index++;
        LoadImage();
    };

    document.getElementById("Container").appendChild(img);
}

这将将图像添加到容器(ID为$ $ c $的元素c>容器)一个接一个,实时测试用例: http://jsfiddle.net/yahavbr/vkQQ7/

This will add the images to the container (element with ID Container) one by one, live test case: http://jsfiddle.net/yahavbr/vkQQ7/

这是简单的JS,随时询问有关任何部分的详细说明。 :)

This is plain JS, feel free to ask about any part for elaboration. :)

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

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