下面的代码块中列出了Math.random
。每次刷新或重新加载页面时,我都会尝试显示图像。虽然,我知道的唯一方法是以数学方式随机加载它们。问题是,我不希望它们随机加载,我希望它们按照imageArray的顺序加载。有没有办法围绕随机函数,可以按照数组的顺序显示每个图像?
var imageArray = [
[ 'http://example.com/assets/reporter.png', '<style>body{background-image:url(), -webkit-linear-gradient(#f5eddf 0%, #e3cfad 100%);#image{margin-left:500px;}</style>', '' ],
[ 'http://example.com/assets/chair.png', '<style>body{background-image:url(), -webkit-linear-gradient(#7abbe7 0%, #a7dbfa 100%);}</style>', '' ]
];
function doIt()
{
var rand = Math.floor(Math.random()*imageArray.length);
var html = "<a href='"+imageArray[rand][2]+"'><img src='"+imageArray[rand][0]+"' alt='heder' border='0' align='absmiddle' /></a><div>"+imageArray[rand][1]+"</div>";
document.getElementById("image").innerHTML = html;
}
答案 0 :(得分:0)
将数组索引放在cookie或本地存储中。当页面加载时,获取cookie并增加它(如果未设置这是第一次,那么随机选择一个图像)。如果增量达到数组的大小,则回绕到0.然后显示带有该索引的图像。然后保存新的cookie值。
var imageArray = [
[ 'http://example.com/assets/reporter.png', '<style>body{background-image:url(), -webkit-linear-gradient(#f5eddf 0%, #e3cfad 100%);#image{margin-left:500px;}</style>', '' ],
[ 'http://example.com/assets/chair.png', '<style>body{background-image:url(), -webkit-linear-gradient(#7abbe7 0%, #a7dbfa 100%);}</style>', '' ]
];
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function doIt()
{
var rand = getCookie('rand');
if (rand == null) {
rand = Math.floor(Math.random()*imageArray.length);
} else {
rand++;
if (rand >= imageArray.length) {
rand = 0;
}
}
setCookie('rand', rand);
var html = "<a href='"+imageArray[rand][2]+"'><img src='"+imageArray[rand][0]+"' alt='heder' border='0' align='absmiddle' /></a><div>"+imageArray[rand][1]+"</div>";
document.getElementById("image").innerHTML = html;
}