定义两个函数:一个用于下一个,一个用于上一个:
function gotoNext() {
var active = document.querySelector(".carouselImage.carouselActive"); //select active image
if (active == null) { //if no active image select the first
document.querySelector(".carouselImage[imgn='1']").className += " carouselActive";
} else {
active.className = "carouselImage";
var curId = active.getAttribute("imgn"); //imgn of selected image
var next = document.querySelector(".carouselImage[imgn='" + (++curId) + "']"); //next image. if there is no next image select the first
if (next == null) document.querySelector(".carouselImage[imgn='1']").className += " carouselActive";
else next.className += " carouselActive";
}
}
function gotoPrev() {
var active = document.querySelector(".carouselImage.carouselActive"); //select active image
if (active == null) { //if no active image select the first
document.querySelector(".carouselImage[imgn='1']").className += " carouselActive";
} else {
active.className = "carouselImage";
var curId = active.getAttribute("imgn"); //imgn of selected image
var prev = document.querySelector(".carouselImage[imgn='" + (--curId) + "']"); //prev image. if there is no prev image select the last
if (prev == null) document.querySelector(".carouselImage[imgn='4']").className += " carouselActive";
else prev.className += " carouselActive";
}
}
注意:最好将 className = ... 替换为可以删除或添加类的函数。例如 jquery 有 removeClass("className") 和 addClass("className")。还有一些没有 jquery 的实现。