问题描述
就像我的标题所说的那样,我正在尝试在图像上进行不透明(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;
}