我正在使用这个脚本来旋转和更改图像,当页面刷新它工作正常,但有时它会在更改为新图像之前多次加载相同的图像,有没有办法解决这个问题?
var theImages = [
"1.jpg",
"2.jpg",
"3.jpg"
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("headerbanner").src = theImages[x];
}
onload=changeImage
要实现所需的图像旋转行为,您需要在页面加载之间“记住”某些状态(即以前的图像)。一个简单的方法是使用LocalStorage API。
例如,您可以通过以下方式检索以前存储的键值:
let lastIndex = localStorage.getItem('last_index');
然后使用它来控制从阵列中显示的图像。您还可以使用:
localStorage.setItem('last_index', `${ lastIndex }`)
要更新存储的值,请为下一页重新加载。这些可能会与您的代码集成,如下所示:
/* Get the last stored index, and parse to an integer */
let lastIndex = Number.parseInt(localStorage.getItem('last_index'))
if(Number.isNaN(lastIndex)) {
/* If we got an invalid index (ie no previously stored value) set to default 0 */
lastIndex = 0;
}
else {
/* Otherwise increment the index counter. This is going to cause the image to
change every page load */
lastIndex ++;
}
/* Remember the updated index for future reloads */
localStorage.setItem('last_index', `${ lastIndex }`)
var theImages = [
"1.jpg",
"2.jpg",
"3.jpg"
];
function changeImage(){
var size=theImages.length;
/* Use the modulo operators to get x based on lastIndex, and the total number
of images */
var x = lastIndex % size;
document.getElementById("headerbanner").src = theImages[x];
}
window.onload=changeImage
请记住,LocalStorage API将值设置为strings
,这就是Number.parseInt()
等必需的原因。
刷新后实现旋转的一种好方法是将以前的图像索引保存在URL中并每次更改它。
1)你登陆页面,查询参数图像为空,你得到索引为1的图像,你将你的网址设置为mysite.com?imageid=1
2)你刷新,查询参数是1,你在网址中将它设置为2并显示图像(这里没有随机性,但你永远不会得到相同的图像)
3)实现自定义逻辑以适应任何索引,你可以实现随机性!==以前的图像id总是得到一个带有递归while循环的不同图像:
while (newImageId === queryParam.imageId) { getRandomImageId(queryParam.imageId)}
我在手机上无法编写代码,但您可以使用window.location作为网址
将当前图像保存到本地会话中。
localStorage.setItem('lastImage', imageIndex);
页面加载后......
localStorage.getItem('lastImage');
...并将其从随机机制中排除或永远迭代。