javascript实现background 定时循环随机背景图

180it 2019-10-06 PM 2632℃ 0条

javascript实现background 定时循环随机背景图

在做一个东西的时候,想弄一个随机背景图!

发现刷新变动的图不好玩,于是用setInterval,定时器来设置一个

案例1 - 采用API接口

setInterval('Getbg();', 1000);
function Getbg(){
var randomBgIndex = Math.round( Math.random() * 166 );
//输出随机的背景图
document.body.style.background="#9E9E9E url(http://api.yum6.cn/360img?"+randomBgIndex+") no-repeat ";
}
利用杨小姐的壁纸API接口实现,第一行的1000是切换时间,这里是毫秒单位!

案例2 - 固定图片

var bodyBgs = [];
bodyBgs[0] = "https://ww1.sinaimg.cn/large/87c01ec7gy1fshdwv00e9j211y0lcjs7.jpg";
bodyBgs[1] = "https://ww3.sinaimg.cn/large/87c01ec7gy1fshdwv56rfj21hc0u0n05.jpg";
bodyBgs[2] = "https://ww3.sinaimg.cn/large/87c01ec7gy1fshdwv5u70j21hc0u0n04.jpg";
bodyBgs[3] = "https://ww4.sinaimg.cn/large/87c01ec7gy1fshdwv8wc2j21hc0u0q5d.jpg";
bodyBgs[4] = "https://ww1.sinaimg.cn/large/87c01ec7gy1fshdwva5i5j21hc0u0q66.jpg";
bodyBgs[5] = "https://ww4.sinaimg.cn/large/87c01ec7gy1fshdwvjc6rj21hc0u0tnw.jpg";
bodyBgs[6] = "https://ww1.sinaimg.cn/large/87c01ec7gy1fshdwvw3hsj21hc0u044j.jpg";
bodyBgs[7] = "https://ww4.sinaimg.cn/large/87c01ec7gy1fshdww034zj21hc0u0jvv.jpg";
bodyBgs[8] = "https://ww4.sinaimg.cn/large/87c01ec7gy1fshdww0q12j21hc0u0tbu.jpg";
bodyBgs[9] = "https://ww1.sinaimg.cn/large/87c01ec7gy1fshdww62pdj21hc0u07b7.jpg";
bodyBgs[10] = "https://ww1.sinaimg.cn/large/87c01ec7gy1fshdww8nc0j21hc0u0wjv.jpg";
setInterval('Getbg();', 1000);
function Getbg(){
var randomBgIndex = Math.round( Math.random() * 10 );
//输出随机的背景图
document.body.style.background="#9E9E9E url("+ bodyBgs[randomBgIndex] +") no-repeat ";
}
这里用的固定地址,用的新浪图床,喜欢的话可以自己扩充图片,我这里简短的展示了10个图片!

而且这样结局了https的问题!

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

javascript实现background 定时循环随机背景图