[英]Background image isn't changing
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))] + ')';
}
How to set background in css 如何在css中设置背景
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.