Javascript 幻灯片在使用 LocalStorage 时不起作用



>我有一个JS和html的幻灯片,它工作正常,直到我使用存储在localStorage中的变量来定义页面刷新/重新加载时从哪个幻灯片开始。

什么有效: - 重新加载页面后,幻灯片从所需的幻灯片开始; - 重新加载页面后,在第一个命令转发后,幻灯片开始正常工作。

什么不起作用: - 重新加载页面后,首次向前移动幻灯片始终使幻灯片从第一张幻灯片开始; - 重新加载页面后,首次向后移动幻灯片始终会使本地存储中的变量未定义并且幻灯片消失。

我认为问题出在showSlides((,但我无法理解它是什么。

这是我到目前为止的代码:

// Set local storage
var slideIx = localStorage.getItem('slideIndex');
if (slideIx === null) {
slideIx = 1;
}
var slideIndex = slideIx;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
localStorage.setItem('slideIndex', slideIndex);
console.log(localStorage.getItem('slideIndex'));
} 
// Thumbnail image controls
function currentSlides(n) {
showSlides(slideIndex = n);
localStorage.setItem('slideIndex', slideIndex);
console.log(localStorage.getItem('slideIndex'));
} 
// Show slides
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
} 
// Arrows control
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
e.preventDefault();
plusSlides(-1); //left <- show Prev image
} else if (e.keyCode == '39') {
e.preventDefault();
plusSlides(1); // right -> show next image
}
}; 

非常感谢您的任何提示(!

我认为问题是您需要在操作之前将字符串转换为数字。从 localStorage 检索的值始终是字符串类型,而代码中需要数字。试试这个:

var slideIx = Number(localStorage.getItem('slideIndex') || 1);

(然后不需要下一次检查null(。

我成功地在幻灯片中通过下一个代码刷新页面后显示最后一张图片(您可以在 https://jsfiddle.net/mu9otwcy/1/在这里看到它(:

var myIndex;
if(localStorage.getItem('slideIx') === null){
myIndex = 0;
}
else{
myIndex = localStorage.getItem('slideIx') -1;
}
console.log(myIndex);
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
console.log(myIndex);
if (myIndex > x.length) {
myIndex =  1;
}
x[myIndex-1].style.display = "block";
var slideIx = localStorage.setItem('slideIx',myIndex);
setTimeout(carousel, 3000);
} 

最新更新