2016-02-23 47 views
2

加載背景圖片需要一些時間。加載圖標作爲背景圖片加載

如何檢查背景圖像(使用background-image CSS標籤應用)是否已完成加載?

+0

我建議你添加類似背景image.That將創造更好的用戶體驗的背景顏色。 – vivek

+0

[jQuery加載事件](https://api.jquery.com/load-event/)可能會幫助你。 – Aatman

回答

1

默認情況下,您可以將加載圖標作爲默認背景圖像,然後在緩存加載圖像下載後通過javascript更新CSS。

這裏的顯示技術工作的例子:

$(document).ready(function() { 
 
    var imgSrc = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'; 
 
    var img = new Image(); 
 
    img.onload = function() { 
 
    $("div").css("background-image", "url('" + img.src + "')"); 
 
    }; 
 
    img.src = imgSrc; 
 
});
div { 
 
    background-color: orange; 
 
    padding: 50px; 
 
    color: purple; 
 
    font-weight: bold; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div>. 
 
    <p>This div will have a solid color as background to begin with.</p> 
 
    <p>Watch its background change to an image once it's loaded.</p> 
 
</div>

+0

你好,你的技術很棒,但這隻能用CSS來實現。 CSS將首先展示顏色,然後展示加載後的圖像。但要適應加載GIF它可以是一個偉大的技術:) –