使用Javascript和Jquery从样式表更改背景图像

时间:2018-02-16 14:56:53

标签: javascript jquery

我想创建一个javascript + jquery函数来改变我的css文件中的背景图像。

如果我尝试更改background-color的值,则可以使用background-image

function randomWallpaper()
{
     var wallpapersList = ["1.jpg","9.jpg","3.jpg", "82.jpg"];
     var newWallpaper = Math.floor(Math.random()*5)+0;
     console.log(newWallpaper); //outputs the index
     changeBackground(wallpapersList, newWallpaper);
 }

function changeBackground(wallpapersList, newWallpaper) 
{
     $("body").css("background-image", wallpapersList[newWallpaper]);
}

setInterval(function()
{
     randomWallpaper();
},2500)

CSS

body 
{
    background-image: url('41.jpeg');
}

有谁能帮我理解我错在哪里以及为什么这段代码不起作用? 我正在努力学习js

2 个答案:

答案 0 :(得分:1)

您也需要输入url()

$("body").css("background-image", "url(" + wallpapersList[newWallpaper] + ")" )

(或使用ES6字符串插值语法:)

$("body").css("background-image", `url( ${wallpapersList[newWallpaper]} )` )

答案 1 :(得分:1)

正如其他人指出的那样,它是url()位。还有一些改进空间:

function randomWallpaper()
{
    // In JS we mostly talk about arrays rather than lists
    const wallpapersArray = ["1.jpg","9.jpg","3.jpg", "82.jpg"];
    // Instead of hard-coding 5, use the length of the array (+1)
    const newIndex = Math.floor(Math.random() * (wallpapersArray.length+1));
    // Don't pass the whole array, just pass the URL we need
    changeBackground(wallpapersArray[newIndex]);
 }

function changeBackground(newWallpaperUrl) 
{
    $("body").css("background-image", "url('"+newWallpaperUrl+"')");
}

setInterval(function()
{
    // You forgot an l here
    randomWallpaper();
}, 2500);