我有一个棘手的小问题。我刚开始设计一个带有自行车背景图像的网站。在它工作正常的那一刻,虽然你可以看到加载第一张图像的备用背景图像看起来有点乱。我可以很容易地隐藏这些图像,但我觉得更好的解决方案是允许第一个图像加载到其他图像之前加速页面加载。不幸的是,我无法弄清楚如何将其融入我现有的JS中。
网站的开头是here(可能会在某些时候被破坏,我还在尝试)。
我现在的JS:
function cycleImages(){
var $active = $('#background-cycler .active');
var $next = ($('#background-cycler .active').next().length > 0) ? $('#background-cycler .active').next() : $('#background-cycler img:first');
$next.css('z-index',2);//move the next image up the pile
$active.fadeOut(1500,function(){//fade out the top image
$active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
$next.css('z-index',3).addClass('active');//make the next image the top one
});
}
$(window).load(function(){
$('#background-cycler').fadeIn(1500);//fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()', 7000);
})
HTML:
<div id="background-cycler" >
<script type="text/javascript">
$('#background_cycler').hide();//hide the background while the images load, ready to fade in later
</script>
<img class="active" src="images/bg1.jpg" alt=""/>
<img src="images/bg2.jpg" alt=""/>
<img src="images/bg3.jpg" alt=""/>
<img src="images/bg4.jpg" alt=""/>
<img src="images/bg5.jpg" alt=""/>
</div>
您可以给予的任何帮助将不胜感激! :)
编辑:我遇到的另一个问题是每个页面都需要这个,但我不想每次都重新加载图像。我是否认为图像仍然会被缓存?答案 0 :(得分:0)
以下是我的看法:
http://jsfiddle.net/bortao/9TxED/
隐藏图像元素,仅在触发onload
事件时将其淡入。
是的,浏览器会在整个网站上缓存所有图片。
<强> HTML 强>
<div id="background-cycler" class="background-cycler">
<img id="imgPrev" />
<img id="imgNext" />
</div>
<强> CSS 强>
.background-cycler {
width: 1000px;
height: 600px;
}
.background-cycler img {
position: absolute;
left: 0px;
top: 0px;
}
<强> JS 强>
var imgs = [
'http://ravenstudio.co.uk/izzy/images/bg1.jpg',
'http://ravenstudio.co.uk/izzy/images/bg2.jpg',
'http://ravenstudio.co.uk/izzy/images/bg3.jpg',
'http://ravenstudio.co.uk/izzy/images/bg4.jpg',
'http://ravenstudio.co.uk/izzy/images/bg5.jpg']
var imgNext = document.getElementById("imgNext");
var imgPrev = document.getElementById("imgPrev");
var currentImg = -1;
var MAX_IMAGES = 5;
var CYCLE_DELAY = 2000;
var FADE_DELAY = 1500;
imgNext.onload = function () {
// When finished loading:
$(this).fadeIn(FADE_DELAY, function() {
// When fadeIn ends:
imgPrev.src = imgs[currentImg]; // Send current image to back
}); // Fade in loaded image
window.setTimeout('cycleImages()', CYCLE_DELAY + FADE_DELAY); // Set next cycle
};
cycleImages = function () {
currentImg++;
if (currentImg == MAX_IMAGES) currentImg = 0;
imgNext.style.display = "none"; // Hide before loading
imgNext.src = imgs[currentImg]; // Load new image.
// After imgNext finish loading, onload above will be called
}
cycleImages(); // Call the first cycle