How to show loading gif while image preview loading via javascript

孤街浪徒 提交于 2019-12-11 22:57:28

问题


On my page i am using links with image preview.

When you go on link with mouse it show a preview image.

Here is demo : http://cssglobe.com/lab/tooltip/03/

i want to show loading gif while image preiview loading.

Loading gif like this : http://i.imgur.com/54cQB45.gif

here is my javascript code ;

this.screenshotPreview = function(){   
        /* CONFIG */

                xOffset = 10;
                yOffset = 30;

                // these 2 variable determine popup's distance from the cursor
                // you might want to adjust to get the right result

        /* END CONFIG */
        $("a.screenshot").hover(function(e){
                this.t = this.title;
                this.title = "";       
                var c = (this.t != "") ? "<br/>" + this.t : "";
                $("body").append("<p id='screenshot'><img src='"+ this.rel +"' alt='url preview' />"+ c +"</p>");                                                                
                $("#screenshot")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px")
                        .fadeIn("fast");                                               
    },
        function(){
                this.title = this.t;   
                $("#screenshot").remove();
    });
        $("a.screenshot").mousemove(function(e){
                $("#screenshot")
                        .css("top",(e.pageY - xOffset) + "px")
                        .css("left",(e.pageX + yOffset) + "px");
        });                    
};


// starting the script on page load
$(document).ready(function(){
        screenshotPreview();
});

and html codes ;

<a href="Link" class="screenshot" rel="image link">Link Name</a>

so how can i do ? Any ideas ?


回答1:


You could use a variation of the following code snippet to trigger an event once it's loaded:

var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
    .load(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
            alert('broken image!');
        } else {
            $("#something").append(img);
        }
    });


来源:https://stackoverflow.com/questions/17901159/how-to-show-loading-gif-while-image-preview-loading-via-javascript

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