第一部分
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type = "text/javascript" >
window.onload=function(){
var imgs =["https://a.xn--xu0a.cn?86", "https://xn--xu0a.cn/api/dn?8261", "https://xn--xu0a.cn/api/dn?826"]; //(设定想要显示的图片)
var i = 0;
var body=document.getElementById("body");//获取DIV对象
body.style.background="url(https://xn--xu0a.cn/api/dn?87)"; //设置图片的初始图片为该路径的图片
function time(){
i++;
i=i%3; // 超过2则取余数,保证循环在0、1、2之间
body.style.background="url("+imgs[i]+")";
}
setInterval(time,2000);//循环调用time1()函数,时间间隔为2000ms
//setInterval()函数,按照指定的周期(按毫秒计)来调用函数或表达式
}
</script>
</head>
<body id="body">
</body>
</html>
第二部分
<script type="text/javascript">
function change(){
var bodyBgs = [];
bodyBgs[0] = "img/0.jpg";
bodyBgs[1] = "img/1.jpg";
bodyBgs[2] = "img/2.jpg";
bodyBgs[3] = "img/3.jpg";
bodyBgs[4] = "img/4.jpg";
bodyBgs[5] = "img/5.jpg";
bodyBgs[6] = "img/6.jpg";
bodyBgs[7] = "img/7.jpg";
bodyBgs[8] = "img/8.jpg";
bodyBgs[9] = "img/9.png";
bodyBgs[10] = "img/10.jpg";
bodyBgs[11] = "img/11.png";
bodyBgs[12] = "img/12.png";
bodyBgs[13] = "img/13.png";
bodyBgs[14] = "img/14.png";
bodyBgs[15] = "img/15.png";
bodyBgs[16] = "img/16.png";
bodyBgs[17] = "img/17.png";
bodyBgs[18] = "img/18.png";
bodyBgs[19] = "img/19.jpg";
bodyBgs[20] = "img/20.jpg";
bodyBgs[21] = "img/21.jpg";
bodyBgs[22] = "img/22.jpg";
bodyBgs[23] = "img/23.jpg";
bodyBgs[24] = "img/24.jpg";
bodyBgs[25] = "img/25.jpg";
bodyBgs[26] = "img/26.png";
//注意 bodyBgs[26] 26是当前序号, 按照顺序添加或删除即可, 但是序号必须是连续的 //bodyBgs[] = "";
var randomBgIndex = Math.round( Math.random() * 26 );//这里的26是随机取值范围, 取最后一个 bodyBgs[*] 的值即可
//document.write('<style>html{background-image:url(' + bodyBgs[randomBgIndex] + ')}</style>');
var img1= document.getElementById('bgimg');
img1.style.backgroundImage='url(' + bodyBgs[randomBgIndex] + ')';
window.setTimeout(function(){change()},10000);//图片切换时间 1000=1s
}
change();
</script>
参考:
js实现自动更换页面背景图片 - 发哥成长日志 - 博客园
https://www.cnblogs.com/shnfg/p/7829567.html