我花了半天时间研究这个问题,但似乎没有解决办法。我正在尝试在slideshow-container
内部更改的图片上制作“淡入淡出”动画。我创建了fade
作为照片容器。这是HTML代码:
changePic()
函数负责更改图片,它可以正常工作,但是我仍然无法获得褪色效果。您知道这段代码有什么问题吗?
var slideIndex = 1;
showSlides(slideIndex);
function changePic(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
const urls = [
"https://www.dike.lib.ia.us/images/sample-1.jpg",
"https://www.dike.lib.ia.us/images/sample-2.jpg",
"https://www.dike.lib.ia.us/images/sample-3.jpg"
];
var picture = document.getElementById("pic");
if(n>urls.length){slideIndex = 1}
if(n<1){slideIndex = urls.length}
picture.src = urls[slideIndex-1];
}
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
<div class="slideshow-container">
<div class="fade">
<img id="pic">
</div>
<a class="prev" onclick="changePic(-1)">Previous</a>
<a class="next" onclick="changePic(1)">Next</a>
</div>
答案 0 :(得分:0)
您可以在图像上添加动画(我在图像上添加了名为“ fadeImage”的类)。然后单击,然后再次删除并添加相同的类。 另外,在添加类之前,请不要忘记使用offset trigger a reflow。
picture.classList.remove("fadeImage");
void picture.offsetWidth;
picture.classList.add("fadeImage");
请参见下面的代码段
var slideIndex = 1;
showSlides(slideIndex);
function changePic(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
const urls = [
"https://www.dike.lib.ia.us/images/sample-1.jpg",
"https://www.dike.lib.ia.us/images/sample-2.jpg",
"https://www.dike.lib.ia.us/images/sample-3.jpg"
];
var picture = document.getElementById("pic");
if(n>urls.length){slideIndex = 1}
if(n<1){slideIndex = urls.length}
picture.src = urls[slideIndex-1];
picture.classList.remove("fadeImage");
void picture.offsetWidth;
picture.classList.add("fadeImage");
}
.fadeImage {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
<div class="slideshow-container">
<div class="fade">
<img id="pic" class="fadeImage">
</div>
<a class="prev" onclick="changePic(-1)">Previous</a>
<a class="next" onclick="changePic(1)">Next</a>
</div>