我前一陣子,我認爲是你在找什麼了這個簡單的js script
+ css
爲一個項目類似的東西。這是一件likee這樣的:
HTML:
<body>
<div id="BG"></div>
<div class="content">
Your content goes here
</div>
</body>
CSS:
body{
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-repeat: no-repeat;
height: 100vh;
}
#BG{
height: auto;
background-image: url('http://www.hdwallpaperscool.com/wp-content/uploads/2013/10/top-beach-hd-wallpaper.jpg');
background-repeat: no-repeat;
position: absolute;
z-index: -1;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 100vh;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
.content{
font-size:22px;
font-weight: bold;
color:#F3D026;
line-height: 24px;
}
的javascript:
var imgArr = new Array(
'http://www.hdwallpaperscool.com/wp-content/uploads/2013/10/top-beach-hd-wallpaper.jpg',
'http://www.hdwallpapersnew.net/wp-content/uploads/2015/09/awesome-sea-wide-hd-wallpaper-images-full-free.jpg',
'http://www.hdwallpapersnew.net/wp-content/uploads/2015/09/beautiful-sea-wide-hd-desktop-background-wallpaper-photos-full-free.jpg'
);
var nextBG = 0;
var BGPath = imgArr[nextBG];
$(document).ready(function(){
// ### Autoload BG images
var preloadArr = new Array();
for (var i = 0; i < imgArr.length; i++){
preloadArr[i] = new Image();
preloadArr[i].src = imgArr[i];
};
// ### Random background switcher
setInterval(BGSwitch, 5000);
});
// BG SWITCH
function BGSwitch(){
//Set the background
$('body').css('background-image', 'url('+BGPath+')');
//Increment BG
if(nextBG >= imgArr.length - 1)
nextBG = 0;
else
nextBG++;
//make bg invisible
$('#BG').css('opacity', 0);
//set new bg
BGPath = imgArr[nextBG];
$('#BG').css('background-image', 'url('+BGPath+')');
//hardcode fix the height
var docH = $(document).height();
$('#BG').css('height', docH);
//fade it back in
$('#BG').fadeTo(1000, 1);
}
你可以看到演示here
我非常喜歡這個解決方案。謝謝。有沒有一種方法可以逐個加載這些圖像?對不起,我忘了在我原來的問題上加入這個。這是我正在考慮的其他事情。它很容易做到嗎? – mapr
這應該不是問題,但每個背景都需要它自己的一個元素。如果有最多兩個疊加圖像,則可以使用':before'和':after'僞。隨着更多,你可能會更好的'真實'的元素,具有'絕對位置'。我會更新答案並添加幾個按鈕,以便隨時淡入。 – Shikkediel
太棒了,謝謝。所以你的意思是說,如果我超過2個,那麼基本上我可以複製爲'#hero' div做了什麼,然後在HTML/CSS中給它一個新的唯一名稱,對吧?例如'#hero-2'。 – mapr