[英]Preload image to change css background from a url link
我正在從我的未飛濺集合( https://unsplash.com/collections/3132360/dashboard )加載圖像,並更改了主體的背景圖像(通過CSS)。 可以,但是更改會有延遲。 有沒有一種方法可以預加載圖像,甚至可以淡入/淡出它們?
我已經嘗試過JavaScript的新Image(),但這是針對HTML圖像而不是CSS。
提前致謝 :)
這是jQuery:
$('document').ready(function(){
var x = 0;
loadImage(x);
});
function loadImage(x) {
x +=1;
var image = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x;
setTimeout(function() {
imgSwap(image, x);
}, 30000)
}
function imgSwap(image, x){
$('body').css('background-image', 'url(' + image + ')');
loadImage(x);
}
您可以在CSS中將默認圖像添加到人體樣式中以顯示預加載圖像。
body{
background-image: url("http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/5-1.gif");
background-repeat: no-repeat;
}
現在可以使用img.src作為CSS的背景URL來更新此更新的代碼,從而根據需要刷新圖像。 僅使用image變量作為URL。
$('document').ready(function(){
var x = 0;
loadImage(x);
});
function loadImage(x) {
x +=1;
var image = new Image()
image.src = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x;
setTimeout(function() {
imgSwap(image, x);
}, 30000)
}
function imgSwap(image, x) {
$('body').css('background-image', 'url(' + image.src + ')');
loadImage(x);
}
我認為,如果您可以包括以下javascript代碼和CSS,則可以完全填充您要實現的功能
function preloader() { if (document.getElementById) { document.getElementById("preload-01").style.background = "url(http://domain.tld/image-01.png) no-repeat -9999px -9999px"; document.getElementById("preload-02").style.background = "url(http://domain.tld/image-02.png) no-repeat -9999px -9999px"; document.getElementById("preload-03").style.background = "url(http://domain.tld/image-03.png) no-repeat -9999px -9999px"; } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(preloader);
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; } #preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; } #preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }
var x = 0; $('document').ready(function(){ loadImage(x); }); function loadImage(x) { setInterval(function() { var randomId = new Date().getTime(); var image = 'https://source.unsplash.com/collection/3132360/1920x1080#'+x+'?r='+randomId; console.log("x="+x + " " + image); imgSwap(image); x +=1; }, 30000) } function imgSwap(image){ $('body').css('background-image', 'url(' + image + ')'); //$('#bg_img').attr('src', image); }
You can change value of x randomly, but i have found your img provider is not returning the images plz check this first, It is redirecting to some other url <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <!--<img id="bg_img" src="" width=400 height=400/>-->
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.