简体   繁体   English

jQuery背景图片褪色

[英]Background image fading with jQuery

I have a series of images that cycle through a slideshow as css background properties. 我有一系列的图像作为CSS background属性在幻灯片中循环显示。 The code below should also have them fade in and out via jQuery's fadeIn property, but for some reason it does not fade, and simply changes instead. 下面的代码还应该通过jQuery的fadeIn属性使它们淡入和淡出,但是由于某些原因,它不会淡入淡出,而只是进行更改。 Any ideas? 有任何想法吗?

This is a follow up from a comment that was never solved. 这是从未解决的评论的跟进。 Fiddle here: http://jsfiddle.net/5fVZ7/6/ 在这里提琴: http : //jsfiddle.net/5fVZ7/6/

var images=new Array();
images[0]='http://s29.postimg.org/912bsm0mf/dataarancio.jpg';
images[1]='http://s27.postimg.org/y6tl17eb7/velocita.jpg';
var nextimage=0;
doSlideshow();

function doSlideshow(){
    if(nextimage>=images.length){nextimage=0;}
    $('.bkg')
    .css('background-image','url("'+images[nextimage++]+'")')
    .fadeIn(500,function(){
    setTimeout(doSlideshow,4000);
});
}

.fadein changes the opacity of the element, but you are making changes to the background image. .fadein更改元素的不透明度,但是您正在更改背景图像。 Animations can only act on numeric values, there's no way for the browser to calculate a background image that is "between" image1 and image2. 动画只能作用于数值,浏览器无法计算介于image1和image2之间的背景图像。 So instead, try overlaying the images as separate html elements and using fadein to control their visibility in sequence. 因此,请尝试将图像覆盖为单独的html元素,并使用fadein依次控制其可见性。

The answer is to wrap the if statement and css property changes in a fadeOut fucntion, like so: 答案是将if语句和css属性的更改包装在fadeOut功能中,如下所示:

var images=new Array();
images[0]='http://s29.postimg.org/912bsm0mf/dataarancio.jpg';
images[1]='http://s27.postimg.org/y6tl17eb7/velocita.jpg';
var nextimage=0;
doSlideshow();

function doSlideshow(){
  $('.bkg').fadeOut(500,function(){
    if(nextimage>=images.length){nextimage=0;}
    $('.bkg').css('background-image','url("'+images[nextimage++]+'")');
  });

  $('.bkg').fadeIn(500,function(){
    setTimeout(doSlideshow,4000);
  });
}

I think this piece of code is simpler and more effective than many others I've found that do the same thing, including the answer to the duplicate question posted in the comments. 我认为这段代码比我发现的许多其他代码都更简单,更有效,它们执行相同的操作,包括评论中张贴的重复问题的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM