在页面加载时生成随机图像

Generate a random image on page load

我正在尝试在我的网站上使用 JavaScript 函数在加载时拉取随机图像并将其设置为正文背景图像。

我一直在搜索并试图拼凑出一个解决方案,但一直没有成功。

这是我的,

function chatimgset() {  
//declare an array
var randomImage = new Array();  
  
//insert the URL of images in array  
randomImage[0] = "image.png";  
randomImage[1] = "image 2.png";  
randomImage[2] = "image 3.png";  
randomImage[3] = "image 4.png ";  
randomImage[4] = "image 5.png";    
  
//generate a number 
var number = Math.floor(Math.random()*randomImage.length);  
  
//return the images generated by number 
return  
  document.getElementsByTagName("body")[0].setAttribute("background-image", "'"+randomImage[number]+"'");
}

我哪里做错了?

谢谢!

您需要设置样式的 background-image 属性,而不是 background-image 属性。所以这就是你应该写的:

function chatimgset() {
  //declare an array
  var randomImage = new Array();

  //insert the URL of images in array  
  randomImage[0] = "image.png";
  randomImage[1] = "image 2.png";
  randomImage[2] = "image 3.png";
  randomImage[3] = "image 4.png ";
  randomImage[4] = "image 5.png";

  //generate a number 
  var number = Math.floor(Math.random() * randomImage.length);

  //return the images generated by number 
  document.getElementsByTagName("body")[0].style.backgroundImage = `url('${randomImage[number]}')`;
}

要在 body 上设置 background image 你需要这样的东西

document.body.style.backgroundImage = "url('img_tree.png')";

所以试试这个

function chatimgset() {
    //declare an array
    var randomImage = new Array();

    //insert the URL of images in array  
    randomImage[0] = "image.png";
    randomImage[1] = "image 2.png";
    randomImage[2] = "image 3.png";
    randomImage[3] = "image 4.png ";
    randomImage[4] = "image 5.png";

    //generate a number 
    var number = Math.floor(Math.random() * randomImage.length);

    //return the images generated by number 
    return randomImage[number];
}
document.body.style.backgroundImage = "url('" + chatimgset() + "')";