我使用这个脚本在页面刷新时旋转和更改图像,它工作正常,但有时它会在更改为新图像之前多次加载相同的图像,有办法解决这个问题吗?
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 .
例如,您可以通过以下方式检索以前存储的 key 值:
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 将值设置为字符串
,这就是为什么 Number.parseInt()
等是必要的。
关于javascript - 页面刷新时更改图像有时会继续加载相同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170278/