[英]How do I change background image of different divs by Javascript function?
Here is my HTML:
<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(在/ body之前的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文件中指定的默認背景。 我希望函數使用隨機文件名覆蓋它
替換為:
document.getElementsByClassName("bg1")
通過
document.querySelector(".bg1")
並調用函數
完整代碼(我也糾正了其他錯誤):
function genBg() { var randomNum; var imagePath = new Array(359); //array to hold the image filenames for (var 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.querySelector(".bg1").style.backgroundImage = 'url(' + background + ')'; //changes filename //this line is for debug document.querySelector(".bg1").innerHTML = background; } genBg();
.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%; width:200px; height:100px; border:1px solid #000; } .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%; }
<div class="master"> <div class="bg1"></div> <div class="bg2"></div> <div class="bg3"></div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.