2016-10-20 130 views
0

在我的網站上有很多圖片,爲了讓它更快,我只想顯示其中的幾個。然後,如果用戶想要看更多,他只需點擊「顯示更多」按鈕。隱藏的圖像被放置在具有display:none屬性的div中。不幸的是,它們仍然加載(實際上它們不可見,但是它們只是加載)。除非用戶點擊顯示更多內容,否則我應該如何不加載它們?防止加載背景圖片

這部分顯示圖片:

<div id="bx-pager"> 
    <?php 
     for ($i=0; $i < count($this->images); $i++) { 
      echo "<a data-slide-index='" .$i. "' style='background: url(" .$this->baseUrl. "/img/upload/" .$this->images[$i]->image. ") center center no-repeat; background-size: cover;'></a>"; 
      if ($i == 10) { 
       break; 
      } 
     } 
    ?> 

    <p id="show-more-images">Show more images</p> 

    <div id="more-photos" style="display: none;"> 

    <?php 
     for ($i=11; $i < count($this->images); $i++) { 
      echo "<a data-slide-index='" .$i. "' style='background: url(" .$this->baseUrl. "/img/upload/" .$this->images[$i]->image. ") center center no-repeat; background-size: cover;'></a>"; 
     } 
    ?> 
    </div> 
</div> 

這是jQuery的部分負責顯示更多的圖像,如果用戶希望:

<script type="text/javascript"> 
    $(document).ready(function(){ 
     $("#show-more-images").click(function(){ 
      $("#more-photos").toggle(); 
     }) 
    }); 
</script> 

讚賞任何幫助。

回答

1

也許這樣:

使用一個CSS類background: none !important;後來將其刪除。 我有testet它,但我不是真的確定圖像是否加載之前。

$('.image').click(function() { 
 
    $(this).removeClass('hidden'); 
 
});
.image { 
 
    width: 200px; 
 
    height: 100px; 
 
    background-size: cover; 
 
    border: 1px solid #000; 
 
} 
 
.image.hidden { 
 
    background: none !important; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="image hidden" style="background-image:url('http://wallpapercave.com/wp/CpRGNUC.jpg');"> 
 
    click me 
 
</div>

其他解決方案:

以後,您可以通過JavaScript添加background-image規則。只需將圖像網址保存在data-image-url="http://www.your-site/your-image.jpg"中,稍後將其用作background-image即可。

$('.image').click(function() { 
 
    $(this).css('background-image', 'url(' + $(this).attr('data-image-url') + ')'); 
 
});
.image { 
 
    width: 200px; 
 
    height: 100px; 
 
    background-size: cover; 
 
    border: 1px solid #000; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="image" data-image-url="http://wallpapercave.com/wp/CpRGNUC.jpg"> 
 
    click me 
 
</div>

0

你可以動態地生成的圖像元素,從而確保您加載速度更快(因爲有在頁面上的文字較少,但實際速度增益將是最小的)。

把你的圖像鏈接在一個這樣的數組:

var links = [ 
    '/image1.png', 
    '/image2.png' 
]; 

然後生成的元素:

$("#show-more-images").click(function(){ 
    var link, $el; 
    for (var i=0; i<links.length; i++) { 
     link = links[i]; 
     $el = $('<a>').attr('style', 'background: url(' + link + ')'); 
     $el.appendTo($('#more-photos')) 
    } 
}); 
0

您可以後加載圖像/秒「顯示更多」點擊它使用Ajax請求。顯示:如果您希望獲得更多性能,則無效,因爲正如您所說,它甚至會加載顯示:無。