1 回答
TA贡献1784条经验 获得超8个赞
您只需要确保最初加载所有图像以进行转换,或者每次调用新图像时都会突然更改,因为它将加载或者您必须等待一个循环,因为您的脚本将加载该周期内的图像。
var images = new Array(
'https://picsum.photos/id/0/300/300',
'https://picsum.photos/id/10/300/300',
'https://picsum.photos/id/15/300/300'
);
var i = 0;
function swap() {
var elm = document.querySelector('.box');
if (i >= images.length) {
i = 0
};
elm.style.backgroundImage = 'url(' + images[i] + ')';
i += 1;
}
window.onload = setInterval(swap, 2000);
.box {
transition: background-image linear 0.5s;
width: 200px;
height: 200px;
background-size: cover;
/* This will force the initial load of all the images*/
background-image:
url(https://picsum.photos/id/0/300/300),
url(https://picsum.photos/id/10/300/300),
url(https://picsum.photos/id/15/300/300);
}
<div class="box"></div>
在上面,您只会在某些浏览器(如 chrome)上褪色。这是我将考虑另一层并依赖不透明度变化的另一个想法:
var images = new Array(
'https://picsum.photos/id/0/300/300',
'https://picsum.photos/id/10/300/300',
'https://picsum.photos/id/15/300/300'
);
var i = 0;
function swap() {
var elm = document.querySelector('.box');
if (i >= images.length) {
i = 0
};
elm.style.backgroundImage = 'url(' + images[i] + ')';
i += 1;
}
window.onload = setInterval(swap, 2000);
.box {
width: 200px;
height: 200px;
background-size: 0 0;
/* This will force the initial load of all the images*/
background-image:
url(https://picsum.photos/id/0/300/300),
url(https://picsum.photos/id/10/300/300),
url(https://picsum.photos/id/15/300/300);
position:relative;
z-index:0;
}
.box:before {
content:"";
position:absolute;
z-index:-1;
top:0;
left:0;
right:0;
bottom:0;
background-image:inherit;
background-size:cover;
animation:op 1s alternate linear infinite 1s;
}
@keyframes op {
to {
opacity:0;
}
}
<div class="box"></div>
添加回答
举报