我不知道我是否在混合东西,但是我无法在个人项目中更改div的背景gif。
我有一个div:
<div id="intro" class="view">
....
</div>
和CSS:
#intro {
background: url("../url/to/gif.gif") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
因此,在加载页面后,如果用户更改了音乐播放器的歌曲,则我已设置了更改背景gif的功能:
let cover = document.getElementById('intro');
let gifs = ['../img/gif1.gif', '../img/gif2.gif', '../img/gif3.gif', '../img/gif4.gif'];
let actual_gif_index = 0;
function changeGif() { // It's called on the music player
randomGifIndex();
cover.background = "url('" + gifs[actual_gif_index] + "') no-repeat center center fixed";
}
function randomGifIndex() {
let randomIndex = actual_gif_index;
while (randomIndex === actual_gif_index) { //make sure to get the different index
randomIndex = Math.floor(Math.random() * gifs.length);
}
actual_gif_index = randomIndex;
}
但是背景没有改变...我尝试过.style.background
或.style.backgroundImage
,但也无法正常工作。
我的错误在哪里,或者我必须更改哪个属性?我有点困惑。
问候
您需要更改.style.background属性-而不是.background属性。查阅此文档:style.background
您应该对单引号进行换码并添加.style以获取属性背景
function changeGif() { // It's called on the music player
randomGifIndex();
cover.style.background = "url(\'" + gifs[actual_gif_index] + "\') no-repeat center center fixed";
}