当页面滚动时,我正在使用Jquery来改变图像的来源。但是,目前它们在显示时正在加载,我希望它们在显示之前预先加载几个图像。
HTML
<img src="/img/1.jpg" />
JQuery的
$(window).load(function(){
// Array of images to swap between
var images = [/img/1.jpg, /img/2.jpg, /img/3.jpg, /img/4.jpg];
var totalImages = images.length;
var documentHeight = $(document).height();
// Work out how often we should change image (i.e. how far we scroll between changes)
var scrollInterval = Math.floor(documentHeight / totalImages);
$(document).scroll(function () {
// Which one should we show at this scroll point?
i = Math.floor($(this).scrollTop() / scrollInterval);
// Show the corresponding image from the array
$('img').attr('src', images[i]);
});
});//]]>
CSS
img {
position: fixed;
top: 0;
left: 0;
height: 100%;
}
body {
height: 5000px;
}
尝试。 我想在此添加与此类似的内容,
$(document).scroll(function () {
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
(new Image()).src = this;
});
}
i = Math.floor([i]+'1');
preload([[i]]);
}
但无法想象如何编码......(JS新手)
答案 0 :(得分:0)
在你的循环中。
var nextTenImages = images.slice(i, i+10);
// preload the next image
preload(nextTenImages);
JSFiddle:http://jsfiddle.net/gvee/ygkWH/8/
编辑:相信以下有关预加载图片的SO主题:Preloading images with jQuery