首页 > 解决方案 > 将数组结果添加到字符串

问题描述

这是一个随机显示应该显示什么图片的小脚本。我可以轻松地将其设置为<img>using document.getElementById("pic").src = randPics[randNumGen],但background标签要求我使用url()。如何设置document.body.style.background为“url(以及此处的随机图像)”?请不要使用 JS 库。

const randPics = ["https://i.ibb.co/6JBbMYm/pic1.jpg", "https://i.ibb.co/rHjTdfc/pic2.jpg"];

window.onload = choosePicture();

function choosePicture() {
  let randNumGen = Math.floor(Math.random() * randPics.length);
  console.log(randNumGen);
  document.body.style.background = "randPics[randNumGen]";
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="styles.css">
  <script async src="index.js" type="text/javascript"></script>
</head>

<body>
  <img width="500px" src="#" alt="pic" id="pic">
</body>

</html>

标签: javascripthtmlmathrandombackground

解决方案


var url = randPics[randNumGen];

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

推荐阅读