使用CSS过渡和jQuery更改DIV的背景:
var images = [
'http://placehold.it/1000x1000',
'http://placehold.it/999x999',
'http://placehold.it/888x888',
];
target.css('background-image', 'url(' + images[bii] + ')');
CSS
#target, #target-cached {
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
-webkit-transition: all 300ms ease-in 200ms;
-moz-transition: all 300ms ease-in 200ms;
-o-transition: all 300ms ease-in 200ms;
transition: all 300ms ease-in 200ms;
}
这很有效,但是第一次迭代数组时转换非常缓慢,因为它在图像仍在下载时试图制作动画。已下载图像后,过渡动画非常流畅。
如果图像尚未加载,如何防止转换?
答案 0 :(得分:0)
这个光插件的例子:Scott Robbin的后伸http://srobbin.com/jquery-plugins/backstretch/。它适用于你的小提琴例子:)
var images = [
'http://placehold.it/1000x1000',
'http://placehold.it/999x999',
'http://placehold.it/888x888',
];
var target = $('#target');
var target2 = $('#target-cached');
var bii = 1;
var maxBii = 3;
target.backstretch(images[0]+ '?r=' + Math.random(),{duration: 3000, fade: 750});
target2.css('background-image', 'url(' + images[0] + ')');
setInterval(function() {
target.backstretch(images[bii]+ '?r=' + Math.random(),{duration: 3000, fade: 750});
target2.css('background-image', 'url(' + images[bii] + ')');
bii++;
if (bii >= maxBii) bii = 0;
console.log(bii);
}, 1500);
#target, #target-cached {
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
-webkit-transition: all 300ms ease-in 200ms;
-moz-transition: all 300ms ease-in 200ms;
-o-transition: all 300ms ease-in 200ms;
transition: all 300ms ease-in 200ms;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
Always new images
<div id="target">
</div>
<br />
<br />
Cached images
<div id="target-cached">
</div>