Here is my HTML:
如何通過Javascript函數更改不同div的背景圖像?
<link href="styles.css" rel=stylesheet>
<title>
Gallery
</title>
</head>
<body>
<div class="master">
<div class="bg1"></div>
<div class="bg2"></div>
<div class="bg3"></div>
...
CSS:
.bg1{
height: 100%;
background-image: url("assets/pi/file-1.jpg");
background-size: contain;
margin: auto;
background-attachment: fixed;
background-repeat: no-repeat;
background-position: center;
max-height:100%;
max-width: 100%;
}
.bg2{
height: 100%;
background-image: url("assets/pi/file-2.jpg");
background-size: contain;
margin: auto;
background-attachment: fixed;
background-repeat: no-repeat;
background-position: center;
max-height:100%;
max-width: 100%;
}
...
的Javascript(在HTML結束前/體):
<script type="text/javascript">
function genBg() {
var randomNum;
var imagePath = new Array(359); //array to hold the image filenames
for (int i=1; i<=359; i++){
imagePath[i]= '\"assets/pi/file-'+i+'.jpg\"';// files are named as
//'file-1, file-2..so
//this loop stores the
//names in array
randomNum = Math.floor(Math.random() * 359);
var background = imagePath[randomNum]; // takes a random filename and
//stores it in var background
document.getElementsByClassName("bg1").style.backgroundImage ='url(\"'+background+'\")'; //changes filename
}
</script>
根據這段代碼,div class =「bg1」的背景應該是隨機的,但它不起作用,它採用了css文件中指定的默認背景。我希望函數覆蓋是一個隨機文件名
你在CSS'bg1'寫時,你應該寫'.bg1' – Core972
複製粘貼錯誤,對不起,編輯它。 – MinorityDev
[getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)將返回一個對象數組。如果你確定只有一個比'document.getElementsByClassName(「bg1」)[0] .style ...'要好,否則你需要一個循環,就像[上一個例子在這裏](https://www.w3schools。 COM/JSREF/met_document_getelementsbyclassname.asp)。歡呼 – skobaljic