在许多练习中,我尝试仅使用Vanilla Javascript创建灯箱画廊。目前,它实际上只是简单创建的,因此请记住这一点。无论如何,问题是当我单击上一个按钮时,它与下一个按钮一样工作。我不明白为什么。您能给我一个提示还是建议一些更好的逻辑?谢谢
let lightbox = document.getElementById("lightbox");
let lightboxTitle=document.getElementById("lightTitle");
let closeBtn=document.getElementById("close");
let nextBtn=document.getElementById("next");
let prevBtn=document.getElementById("prev");
let mainPic=document.getElementById("mainPic");
let picList = document.getElementsByClassName("thumbnails");
let gallery = document.getElementById("gallery");
let navbar = document.getElementById("navbar_main");
let footer = document.getElementById("main_footer")
let thumbnails = [
{
src: "img/10.jpg",
title: "Schody 1",
class: "thumbnails",
position: 1
},
{
src: "img/17.jpg",
title: "Schody 2",
class: "thumbnails",
position: 2
},
{
src: "img/19.jpg",
title: "Schody 3",
class: "thumbnails",
position: 3
},
{
src: "img/31.jpg",
title: "Schody 4",
class: "thumbnails",
position: 4
}
];
for (let i=0;i<thumbnails.length;i++){
let picBox = document.createElement("div")
let newPic = document.createElement("img");
let newPicTitle = document.createElement("h6");
picBox.className="picBox";
newPic.src = thumbnails[i].src;
newPic.className=thumbnails[i].class;
newPicTitle.innerHTML = thumbnails[i].title;
newPic.position = thumbnails[i].position;
picBox.appendChild(newPic);
picBox.appendChild(newPicTitle);
gallery.appendChild(picBox);
picList[i].addEventListener("click",(e) => {
lightbox.style.display="flex";
mainPic.src=e.target.src;
mainPic.position=e.target.position;
lightboxTitle.innerHTML=e.target.nextElementSibling.innerHTML;
navbar.style.display="none";
footer.style.display="none";
})
}
closeBtn.addEventListener("click",()=>{
lightbox.style.display="none";
navbar.style.display="";
footer.style.display="";
});
nextBtn.addEventListener("click",()=>{
let mainPosition = parseInt(mainPic.position);
let i= mainPosition++;
mainPic.src = thumbnails[i].src;
mainPic.position = thumbnails[i].position;
lightboxTitle.innerHTML = thumbnails[i].title;
});
prevBtn.addEventListener("click",()=>{
let mainPosition = parseInt(mainPic.position);
let i= mainPosition--;
mainPic.src = thumbnails[i].src;
mainPic.position = thumbnails[i].position;
lightboxTitle.innerHTML = thumbnails[i].title;
});
对于完整的项目Visit my repo