参见英文答案 >
Load Random Images from Directory 5个
我目前在我的网站上有一张停滞不前的图像:
我目前在我的网站上有一张停滞不前的图像:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link href="/stylesheets/normalize.css" media="all" rel="stylesheet" /> <link href="/stylesheets/master.css" media="all" rel="stylesheet" /> <script> window.onload = function () { var images = [],i=1,indexImages = true,prefix = '../image/',extension = '.jpg'; while (indexImages) { var a = new XMLHttpRequest(); a.open('GET',prefix+i+extension,false); a.send(); if (a.status != 404) { i += 1; images.push(prefix+i+extension); } else { indexImages = false; localStorage['backgroundIndex'] = !localStorage['backgroundIndex']?0:+localStorage['backgroundIndex']+2>images.length?0:+localStorage['backgroundIndex']+1; document.body.style.backgroundImage = 'url(' + images[+localStorage['backgroundIndex']] + ')'; } } } </script> <style> body { background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-color: black; border-bottom: 8px solid #7D8A28; } </style> </head> <body> <section id="card"> </section> </body> </html>
只是我希望每次页面刷新时它都是一个不同的图像,所以它会自动更改为2.jpg,3.jpg,10.jpg,等等. (有数百种可供选择)
有人可以帮我解决问题吗?我不是很擅长这个,这是我的第一个网站.
谢谢.
解决方法
您可以使用JavaScript轻松完成.您可以使用所有图像定义一个数组,然后在每次加载页面时创建一个随机数.然后使用随机数访问数组的索引以读取图像的名称.像这样:
var images = ["image1.jpg","image2.jpg","image3.jpg","image4.jpg","image5.jpg"]; var randomNumber = Math.floor((Math.random() * images.length)); //images[randomNumber] contains your random image
希望能帮助到你.问候,
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。