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>
添加回答
舉報