3

如果我有一个包含四个图像的 div

<div id='imgs' class='sectionImage'>
    <img id='imgj1' imgn='1' class='carouselImage carouselActive' src='img/image1.jpg'/>
    <img id='imgj2' imgn='2' class='carouselImage' src='img/image2.jpg'/>
    <img id='imgj3' imgn='3' class='carouselImage' src='img/image3.jpg'/>
    <img  id='imgj4' imgn='4'class='carouselImage' src='img/image4.jpg'/>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

我将如何设置一个数组和函数以通过将活动类移动到下一个图像并继续循环来滚动数组中的四个图像?请只使用 Javascript...没有库

4

1 回答 1

1

定义两个函数:一个用于下一个,一个用于上一个:

    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 的实现。

于 2012-06-29T19:06:14.337 回答