我希望我的网页的背景图片随着下一张图片淡入而淡出,我是这样做的:
var backgrounds = [];
backgrounds[0] = './img/bg.jpg';
backgrounds[1] = './img/bg2.jpg';
backgrounds[2] = './img/bg3.jpg';
function changeBackground() {
currentBackground++;
if(currentBackground > backgrounds.length-1) currentBackground = 0;
$('.bgContainer').fadeOut(1500,function() {
$('.bgContainer').attr('src', backgrounds[currentBackground]);
$('.bgContainer').fadeIn(3000);
});
setTimeout(changeBackground, 5000);
}
并且它工作正常,但是每次下一个图像在任何其他元素中淡出时都会开始掉帧并变得非常滞后。有什么办法可以减少丢帧吗?
.bgContainer{
position:fixed;
z-index: -1;
width:100vw;
height:100%;
top:0;
}
<img class="bgContainer" src = "./img/bg.jpg">
最佳答案
我不知道你是否可以使用 css transitions 来实现浏览器兼容性,但你可以尝试类似的方法:
.bgContainer {
transition: opacity 1500ms ease-in-out;
}
和
$('.bgContainer').css('opacity', 0);
setTimeout(function() {
$('.bgContainer').attr('src', backgrounds[currentBackground]);
$('.bgContainer').css('opacity', 1);
}, 1500);
这样您就不会使用 javascript 来更改 css 属性,而是使用 CSS3 来淡化背景的不透明度。
比 javascript 动画慢得多,但只适用于现代浏览器。 ie10+
关于javascript - Laggy 淡入淡出背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22613078/