尝试在图像上使用不透明度进行过渡



正如我的标题所说,我试图在图像上进行不透明度(0到1,间隔2秒(的转换,但我不知道如何进行。

转换只对第一张图像有效,但对其他图像无效,我不明白为什么。

所以我希望你能帮助我理解我的错误,我是javascript新手。提前谢谢你,这是我的代码

我的HTML文件:

<img src="img/1.jpg" alt="slide-photo">

我的CSS文件:

#slideshow-home img {
width: 100%;
opacity: 0;
transition: 1s ease-in-out;
}

我的JS文件:

var image = document.querySelector('img');
var img = 1 ;
window.setInterval(changeImage, 2000); 
function changeImage() {
image.setAttribute('src', 'img/' + img + '.jpg'); 
image.style.opacity = 1; 
img++; 
if(img === 6) { 
img = 1; 
}
}

这就是我处理图像淡入过渡的方法,好处是它在图像实际加载之前不会启动,所以在中淡入时永远不会出现抖动

JS

var image = document.querySelector('img');
var img = 1;
window.setInterval(changeImage,5000); 
function changeImage() {
image.classList.remove('fadeIn')
image.src = 'img/'+img+'.jpg'
img++
if (img == 6) {
img = 1;
} 
}
image.addEventListener('load', () => { // This function looks at the image and every time an image is loaded i.e whenever it gets a new src, it does a fade in animation
void(image.offsetHeight)
image.classList.add('fadeIn')
})

CSS

我通常用动画来做这件事,比如下面的

#slideshow-home img {
width: 100%;
opacity: 0;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.fadeIn {
animation:fadeIn 2s forwards;
}

最新更新