代码之家  ›  专栏  ›  技术社区  ›  Eli Courtwright

检测特定图像何时完成加载

  •  3
  • Eli Courtwright  · 技术社区  · 16 年前

    我在一个由服务器端CGI程序动态生成的网页上有一个图像。此图像定期由计时器刷新和/或根据用户输入进行更改。所以我有一个javascript函数

    // <img id="screen" src=""> is elsewhere in the page
    function reloadImage() {
        $("#screen").attr("src", make_cgi_url_based_on_form_inputs());
    }
    

    这很好,但有时加载图像需要一段时间。因此,我希望出现一条消息,上面写着“正在加载图像…”,但是当图像加载并显示在浏览器中时,该图像就会消失。

    是否有任何类型的javascript事件可以做到这一点?或者,是否有其他方法可以通过Ajax或其他方式加载/更改/更新图像并在加载完成时进行检测?

    1 回复  |  直到 16 年前
        1
  •  9
  •   marcgg    16 年前

    您可以尝试此jquery解决方案: http://jqueryfordesigners.com/image-loading/

    $(function () {
            var img = new Image();
            $(img).load(function () {
                //$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
                $(this).hide();
                $('#loader').removeClass('loading').append(this);
                $(this).fadeIn();
            }).error(function () {
                // notify the user that the image could not be loaded
            }).attr('src', 'http://farm3.static.flickr.com/2405/2238919394_4c9b5aa921_o.jpg');
        });