[英]Change background-image of a class dynamically on a date using javascript/Jquery?
[英]Change the background-image from the Style Sheet using Javascript and 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
您還需要輸入url()
。
$("body").css("background-image", "url(" + wallpapersList[newWallpaper] + ")" )
(或使用ES6字符串插值語法:)
$("body").css("background-image", `url( ${wallpapersList[newWallpaper]} )` )
正如其他人指出的那樣,它是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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.