猿问

如何将 css 过渡应用于背景图像更改?

如果我使用下面的简单 JS 来更改计时器上的背景图像,我是否可以应用 CSS 过渡来使它们淡入而不是立即交换?


var images = new Array(

     '../images/pic1.jpg'

    ,'../images/pic2.jpg'

    ,'../images/pic3.jpg'

);

var i = 0;


function swap() {

    var elm = document.querySelector('.myCSSClass');

    if (i >= images.length) { i = 0 };

    elm.style.backgroundImage = 'url(' + images[i] + ')';

    i += 1;

}


window.onload = setInterval(swap, 2000);

例如,我正在尝试使用 CSS:


.myCSSClass{

      transition: background-image linear 0.3s;

}

但没有得到任何结果。我觉得这是不可能的,因为 javascript 只是覆盖图像?


DIEA
浏览 165回答 1
1回答

青春有我

您只需要确保最初加载所有图像以进行转换,或者每次调用新图像时都会突然更改,因为它将加载或者您必须等待一个循环,因为您的脚本将加载该周期内的图像。var images = new Array(&nbsp; 'https://picsum.photos/id/0/300/300',&nbsp;&nbsp; 'https://picsum.photos/id/10/300/300',&nbsp;&nbsp; 'https://picsum.photos/id/15/300/300');var i = 0;function swap() {&nbsp; var elm = document.querySelector('.box');&nbsp; if (i >= images.length) {&nbsp; &nbsp; i = 0&nbsp; };&nbsp; elm.style.backgroundImage = 'url(' + images[i] + ')';&nbsp; i += 1;}window.onload = setInterval(swap, 2000);.box {&nbsp; transition: background-image linear 0.5s;&nbsp; width: 200px;&nbsp; height: 200px;&nbsp; background-size: cover;&nbsp;&nbsp;&nbsp; /* This will force the initial load of all the images*/&nbsp; background-image:&nbsp; &nbsp; url(https://picsum.photos/id/0/300/300),&nbsp; &nbsp; url(https://picsum.photos/id/10/300/300),&nbsp; &nbsp; url(https://picsum.photos/id/15/300/300);}<div class="box"></div>在上面,您只会在某些浏览器(如 chrome)上褪色。这是我将考虑另一层并依赖不透明度变化的另一个想法:var images = new Array(&nbsp; 'https://picsum.photos/id/0/300/300',&nbsp;&nbsp; 'https://picsum.photos/id/10/300/300',&nbsp;&nbsp; 'https://picsum.photos/id/15/300/300');var i = 0;function swap() {&nbsp; var elm = document.querySelector('.box');&nbsp; if (i >= images.length) {&nbsp; &nbsp; i = 0&nbsp; };&nbsp; elm.style.backgroundImage = 'url(' + images[i] + ')';&nbsp; i += 1;}window.onload = setInterval(swap, 2000);.box {&nbsp; width: 200px;&nbsp; height: 200px;&nbsp; background-size: 0 0;&nbsp;&nbsp;&nbsp; /* This will force the initial load of all the images*/&nbsp; background-image:&nbsp; &nbsp; url(https://picsum.photos/id/0/300/300),&nbsp; &nbsp; url(https://picsum.photos/id/10/300/300),&nbsp; &nbsp; url(https://picsum.photos/id/15/300/300);&nbsp; position:relative;&nbsp; z-index:0;}.box:before {&nbsp; content:"";&nbsp; position:absolute;&nbsp; z-index:-1;&nbsp; top:0;&nbsp; left:0;&nbsp; right:0;&nbsp; bottom:0;&nbsp; background-image:inherit;&nbsp; background-size:cover;&nbsp; animation:op 1s alternate linear infinite 1s;}@keyframes op {&nbsp; &nbsp;to {&nbsp; &nbsp; &nbsp;opacity:0;&nbsp; &nbsp;}}<div class="box"></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答