jQuery progressbar on changing image .attr('src')

て烟熏妆下的殇ゞ 提交于 2019-12-13 15:44:25

问题


I have an image declared in HTML as:

<img src="images/image_01.gif" id="man_img_file" width="400" height="300" alt="image_01" />

I'm changing the image through jQuery:

$('#man_img_file').attr('src', "images/image_02.gif");

Now I want to display a percentage progress bar while the image loads (ie. while the new src image loads through jQuery). How can this be achieved? Can it be done using the jQuery progressbar?

Note: The images are already in the server and I can get the image size through a PHP script prior loading it.


回答1:


You might not be able to add a progress bar since I don't know a way of determining how much of the image has been loaded just by using Javascript.

However, you could use the Image object and display a rotating "loading" gif while the new image loads:

function LoadNewImage(target, url) {
    var newImage = new Image();

    // some overlay div
    loadingOverlay.show();

    newImage.src = url;

    newImage.onload = function() {
        // image is loaded into browser memory, so will display instantly
        target.attr('src', url);

        // hide the overlay again
        loadingOverlay.hide();
    }
}

Here are some links that might help:

Preload images with javascript

Show a loading overlay




回答2:


Thanks Laurence for sharing.

  1. While changing the 'src' attribute with jQuery, the amount of bytes loaded cannot be checked on the fly (with javascript).
  2. However, while the image is being loaded, a loading message/image can be displayed. (Check the Laurence's answer above for the solution)
  3. As Laurence says, "If you're happy with HTML5 and anything above IE9 you can apparently do this with an XHR: http://blogs.adobe.com/webplatform/2012/01/13/html5-image-progress-events/ (see the sample here: http://blogs.adobe.com/webplatform/files/XHRProgressSample.html?file=XHRProgressSample.html)"


来源:https://stackoverflow.com/questions/12905468/jquery-progressbar-on-changing-image-attrsrc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!