此代码在两个不同图像之间切换背景。然而,当它从第一个图像切换到第二个图像时,在显示图像之前总是有一秒钟的缓冲区,并且这只发生在图像第一次切换时。我怎样才能摆脱缓冲区?
function changeBgColor(){
var img = ['url(img/mechanic.jpg)', 'url(img/start.jpg)'];
var nImg = img.length;
var currentImg = 0;
document.body.style.backgroundImage = "url(img/start.jpg)";
document.body.style.backgroundSize = "cover";
document.body.style.backgroundRepeat = "no-repeat";
var imgChange = setInterval(function(){
document.body.style.backgroundImage = img[currentImg];
document.body.style.backgroundSize = "cover";
document.body.style.backgroundRepeat = "no-repeat";
if(currentImg == nImg-1){
currentImg = -1;
}
currentImg++;
},10000);
}
最佳答案
这是由于图像加载造成的。图像加载后就会被缓存,因此第一次加载后问题并不明显。为了解决这个问题,您可以使用 CSS 或 jquery 预加载有问题的图像
CSS
body:after{
display:none;
content: url(img01.png) url(img02.png) url(img03.png) url(img04.png);
}
jQuery
<script>
pic = new Image();
pic2 = new Image();
pic3 = new Image();
pic.src="images/inputs/input1.png";
pic2.src="images/inputs/input2.png";
pic3.src="images/inputs/input3.png";
</script>
关于首次运行时 JavaScript 在背景图像之间切换速度较慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24640219/