這是一個小腳本,隨機化它應該顯示什么圖片。我可以輕松地將其設定為<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>
uj5u.com熱心網友回復:
var url = randPics[randNumGen];
document.body.style.backgroundImage = "url('" url "')";
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362849.html
標籤:javascript html 数学 随机的 背景
下一篇:計數符號變化
