2015-02-09 42 views
0

我目前正在从数据库获取图像的名称到相册并创建图库。我想在点击缩略图时弹出高清图像。我用这段代码来替换弹出式窗口中的图片,以获取特定缩略图:获取时间将图像从服务器加载到浏览器

$(".srcimage").click(function(){ //click is triggered in thumbnail img. 
     $("#popImage").attr("src", " "); //name of popup img that should be HD. 
     var srcimgs = $(this).attr('name'); 
     var name = $(this).attr('data-value'); 
     var srcimg = "<?php echo base_url()."content/uploads/images/"; ?>"+srcimgs; //path of HD image. 
     $("#popImage").attr({ 
      src: srcimg 

     }); 
     $('.modal-title').html(name); 
    }); 

但是它的工作很慢。也就是说,当第一次点击一张图像的缩略图时,该缩略图的HD图像正确加载。再次点击另一个缩略图时,弹出窗口显示以前的HD图像,需要很长时间才能被替换。

我认为这可以通过下载图像从服务器下载到borwser来解决,以便我可以显示加载的时间,直到它的特定缩略图的HD图像尚未加载。

回答

1

您可以使用Image的加载事件。

$(".srcimage").click(function() {   

    $("#popImage").prop("src", ""); //Use prop instead of attr 
    var srcimgs = $(this).attr('name'); 
    var name = $(this).attr('data-value');   

    //Show a loading text 
    $("#loading").text("Loading...");    

    //Initilize a image 
    var img = new Image(); 

    //Set SRC 
    img.src = "<?php echo base_url()."content/uploads/images/"; ?>"+srcimgs; //path of HD image. 

    //Bind load event handler 
    img.onload = function() { 
     //When image is loaded set popImage as src    
     $("#popImage").prop("src", this.src); 

     //Hide loading 
     $("#loading").hide(); 
    }; 


    $('.modal-title').html(name); 
}); 
1

您可以预加载图像。要做到这一点,用JavaScript创建一个img标签,但不要把它插入到DOM

var img = document.createElement("img"); 

然后设置一个事件监听就可以了,找出来的时候,图像满载

img.addEventListener("loaded", function() { 
    // The image is now in the browser's memory. You can insert it 
    // into the DOM without any delay 
} 

然后设置img元素的源,这将再次开始预加载

img.src = "http://example.com/someImg.png"; 

在此之后,把逻辑显示装载

$("#loading").text("Loading..."); 
+0

thanx的答复。我会尽力让你知道。 – 2015-02-09 08:29:39