2015-02-09 54 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