问题
I'm trying to change the background color and a series of images through cross-fade via javascript. In first 3-4 loops both are synchronized (each color in 2 seconds and each image in 2 seconds) but after sometime the background color change slowdown and lags. I want both the elements to change simultaneously at same time. Please Help. FIDDLE- jsfiddle.net/pEHZR
$(function () {
var colors = ['black', 'red', 'blue', 'black'];
var i = 0;
var cont = $('div.container');
var back = $('div.back');
back.css('opacity', 1);
back.css('backgroundColor', colors[0]);
cont.css('backgroundColor', colors[1]);
window.onload = function start() {
setInterval(function () {
anim();
}, 2000);
}
function anim() {
if (i == colors.length - 1) {
i = 0;
return;
}
back.css({
backgroundColor: colors[i],
opacity: 1
});
cont.css({
backgroundColor: colors[i + 1]
});
i++;
back.stop().animate({
opacity: 0
}, 2000, anim);
}
});
$(function () {
$('.fadein img:gt(0)').hide();
setInterval(function () {
$('.fadein :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadein');
}, 2000);
});
回答1:
Removed the setInterval function and put all your code in one place, so now the animation and text are synchronized:
HTML:
<div class="container">
<div class="back"></div>
<div class="main"></div>
</div>
CSS:
.container {
position:absolute;
top:0px;
left:50%;
margin-left:-75px;
width:130px;
height:130px;
border:10px solid yellow;
}
.back {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
.main {
position:relative;
text-align:center;
color:white;
background-color:transparent;
}
JS:
$(function () {
var colors = ['black', 'red', 'blue', 'green', 'black'];
var i = 0;
var cont = $('div.container');
var back = $('div.back');
var main = $('div.main');
back.css('opacity', 1);
back.css('backgroundColor', colors[0]); // start color , fades out
cont.css('backgroundColor', colors[1]); // target color
anim();
function anim() {
if (i == colors.length - 1) {
i=0;
//return; // repeat ad infinitum
}
main.text(colors[i+1]);
var top = (cont.height() - main.height())/2 |0;
main.css('top', top + 'px'); //center text vertically
back.css({
backgroundColor: colors[i],
opacity: 1
});
cont.css({
backgroundColor: colors[i+1]
});
i++;
back.stop().animate({
opacity: 0
}, 2000, anim);
}
});
http://jsfiddle.net/TytSZ/10/
http://jsfiddle.net/TytSZ/12/ (modified algorithm with transparent .png images)
来源:https://stackoverflow.com/questions/17916298/fade-background-color-change-animation-lags-and-slows-down