我正在用Javascript动态更改div的背景图片。
当图像出现在div中时,我希望发生灰度到颜色的过渡。但它只是第一次发生,如果我再次改变图像效果不起作用。
当后台网址发生变化时,如何触发CSS3动画?
我在这个问题上没有Jquery,只有vanilla js
.slide {
width: 100%;
height: 100%;
position: fixed;
animation: filter-animation 8s;
-webkit-animation: filter-animation 8s;
}
-
@keyframes filter-animation {
0% {
filter: grayscale(100%);
transition: all 8s ease;
100% {
filter: grayscale(0%);
}
}
}
JS渲染代码:
function renderCurrentSlide() {
document.getElementById('slide').style.background = "url('" + Image.image_data + "') no-repeat top center fixed";
document.getElementById('image-title').innerHTML = Image.title;
document.getElementById('image-caption').innerHTML = Image.desc;
}
HTML:
<div id="slider-container">
<div class="slider-main">
<div id="gallery">
<ul class="images">
<li class="slide" id="slide"></li>
</ul>
</div>
<div class="caption-and-title-holder">
<div id="image-title"></div>
<div id="image-caption"></div>
</div>
</div>
</div>
答案 0 :(得分:1)
您应该创建一个仅处理动画的类,然后
var images = [
'http://dummyimage.com/500x500/ff000/ffffff?text=1',
'http://dummyimage.com/500x500/00ff00/ffffff?text=2'
]
function renderCurrentSlide() {
var slide = document.getElementById('slide');
slide.classList.remove('filter-animation');
slide.style.background = "url('" + images[0] + "') no-repeat top center fixed";
void slide.offsetWidth;
slide.classList.add('filter-animation');
}
//for demo only
renderCurrentSlide();
images.shift();
setTimeout(renderCurrentSlide, 10000);
&#13;
.slide {
width: 100%;
height: 100%;
position: fixed;
filter: grayscale(100%);
}
.filter-animation {
animation: filter-animation 8s forwards;
-webkit-animation: filter-animation 8s forwards;
}
@keyframes filter-animation {
0% {
filter: grayscale(100%);
}
100% {
filter: grayscale(0%);
}
}
&#13;
<div id="slider-container">
<div class="slider-main">
<div id="gallery">
<ul class="images">
<li class="slide" id="slide"></li>
</ul>
</div>
<div class="caption-and-title-holder">
<div id="image-title"></div>
<div id="image-caption"></div>
</div>
</div>
</div>
&#13;