I'm trying to get a random background image. But when I load the page my background is empty. This is my code:
<html>
<head>
<script>
function random_imglink(){
var myimages=new Array();
myimages[1]="images/1.png";
myimages[2]="images/2.png";
myimages[3]="images/3.png";
myimages[4]="images/4.png";
var count=Math.floor(Math.random() * myimages.length);
if (count==0){
count=1;
}
document.write("'" + myimages[count] + "'");
}
</script>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body background=random_imglink()>
<?php include ("header.php"); ?>
<div align="center" >
<?php include ("main.php"); ?>
<?php include ("footer.php"); ?>
</div>
</body>
</html>
I hope someone has got a solution to this problem?
Add this inside your script tag:
window.onload = function () {
var imgs = [
'images/1.png',
'images/2.png',
'images/3.png',
'images/4.png'
];
document.body.style.background = 'url(' + imgs[Math.round(Math.random() * (imgs.length - 1))] + ')';
}
Don't forget to check if the images really exist.
<script>
window.onload=function(){
var myimages=new Array();
myimages[1]="images/1.png";
myimages[2]="images/2.png";
myimages[3]="images/3.png";
myimages[4]="images/4.png";
var count=Math.floor(Math.random() * myimages.length);
if (count==0){
count=1;}
document.body.style.backgroundImage="url('" + myimages[count] + "')";
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.