使用fadeIn()循环显示背景图像

我正在制作一个带有一些视差图像的响应式网站,第一个图像是一个循环图像,就像一个图像滑块。 我正在使用jquery Cool小猫的响应能力。

我加载的相关jquery插件是:

  

div的css是:

 #slide2 { background-image:url(../images/darkmap.png); height:700px; } 

我发现在这种布局中使用HTML图像作为背景可能会有问题,这就是我通过使用数组避免这种情况的原因:

 var imageIndex = 0; var imagesArray = [ "images/photo1.png", "images/photo2.png", "images/photo3.png" ]; 

我有一个包含在$(document).ready()函数中的代码,它将css背景更改为数组,然后循环遍历数组,我添加了fadeIn()以实现平滑过渡:

 function changeImage(){ var index = imageIndex++ % imagesArray.length; $("#slide2").css("background","url('"+ imagesArray[index] +"')"); } setInterval(changeImage, 5000); changeImage.fadeIn(); 

图像循环工作正常,但由于某种原因fadeIn()不起作用,它只是从一个图像闪烁到另一个图像。 有人可以告诉我我错过了什么吗?

正如其他用户所提到的,你不能在函数上使用.fadeIn() 。 您只能在元素上使用它。

除此之外,您想要做的事情不可能在单个元素上。 一旦更改元素的背景图像,之前的背景图像就会消失。 您将无法将其平滑地淡入其他图像,因为之前的图像已被替换并且不再存在。

您将需要添加多个元素,其中包含您的背景图像,将它们放在彼此的顶部, position: absolute; ,然后你可以使用jQuery淡入或淡出相应的。

HTML

 

使用Javascript

 setTimeout(function(){ $("#background2").fadeIn(); }, 2000); 

JSFiddle演示


您还可以使用数组(如您所述)和2个html元素使其更加动态:一个底部元素和一个顶部元素,您将使用您的背景循环:

 var index = 0; var imagesArray = ["https://placekitten.com/g/500/300", "https://placekitten.com/g/600/300", "https://placekitten.com/g/700/300"]; var background1 = $("#background1"), background2 = $("#background2"); //Set the starting background background2.css("background","url('"+ imagesArray[index] +"')"); setInterval(changeImage, 2000); function changeImage(){ //Make sure that the bottom element has the "old" background background2.css("background","url('"+ imagesArray[index] +"')"); //Hide the top element which we will load the "new" background in now background1.hide(); index++; if(index >= imagesArray.length){ index = 0; } //Set the background of the top element to the new background background1.css("background","url('"+ imagesArray[index] +"')"); //Fade in the top element background1.fadeIn(); } 

JSFiddle演示