1

我有一个网页,里面有一张图片。但是图像会在页面打开几秒钟后加载。我想在图像尚未加载时显示加载 gif,然后每 2 秒检查一次图像是否已加载。加载图像后,我想用图像替换加载 gif。我编写了以下代码:

    <script language="javascript" type="text/javascript">
        function checkImage(src) {
            var img = new Image();
            img.onload = function () {
                // code to set the src on success
                $('#img1').attr('src', 'imageOriginal.jpg');
                $('#img1').removeAttr('width');
                clearInterval(interval);
            };
            img.onerror = function () {
                countErrors = countErrors + 1;
            };

            img.src = src; // fires off loading of image
        }
        var interval;
        var countErrors = 0;
        $(document).ready(function () {
            $('#img1').attr('width', '620px');
            interval = window.setInterval(function () { checkImage('imageOriginal.jpg?id=' + countErrors); }, 2000);
        });
    </script>

                <img borderstyle="solid" bordercolor="black" borderwidth="1px" id="img1" alt="Screenshot" style="max-width:620px;" src="loading.gif" />

它有时有效,有时无效。我什至添加了一个 id 参数来防止缓存。但是即使图像已经加载,也会显示加载 gif。我该如何解决这个问题?

4

2 回答 2

0

If jQuery is involved in your script, one way I've seen it done is by attaching an onload event to the image, similar to what you have there, except that the onload event triggers when the image is in fact loaded. Upon this event you could then hide the loading image. I think it would make more sense to have the loading image be its own separate image and just hide/show it depending on whether your main image is loaded or not.

Example:

$('#img1').load(function() {
    $('#loadingImage').hide();
    $('#img1').show();
});

No need to have this check on an interval. The load event only needs to be attached once and will fire reliably when the image finishes loading.

于 2013-07-11T21:24:34.407 回答
0

考虑添加一个浮动元素作为占位符,其中包含微调器,并在 img.load(而不是 onload)上隐藏浮动 div。使用 img.load 将使您不必进行轮询,并且使用浮动 div 将减少在图像之间转换时任何感知到的“打嗝”。将它们分层也为动画过渡打开了大门。

于 2013-07-11T22:12:36.830 回答