javascript - 单击返回数组中的项目

标签 javascript html arrays

嗨,我正在尝试仅使用 javascript 创建一个 slider ,我将图像放入数组中。到目前为止,我已使其与“下一个”按钮一起使用,但我在“上一个”按钮上遇到困难,我不知道如何开始。我是 javascript 新手,所以如果我的代码效率很低,请告诉我。

这就是我用于“下一步”按钮的内容

function slideRight() {
    index++
    if(index >= slideList.length){
        index = 0;
        slideList[2].style.display = 'none'; 
        circle[index].style.backgroundColor = 'red';
        circle[2].style.backgroundColor = 'black';
    }

    slideList[index].style.display = 'block'; 
    slideList[index-1].style.display = 'none'; 

    circle[index].style.backgroundColor = 'red';
    circle[index-1].style.backgroundColor = 'black';
}

我尝试过使用递减,但不起作用。

这是完整代码的 fiddle fiddle

最佳答案

您可以将其优化为仅对两项作业使用一个函数,如下所示(请参阅 action ):

var slide = document.getElementsByClassName("slide"),//getting slide class as node list
    circle = document.getElementsByClassName("circle"),
    slideList = [slide[0],slide[1],slide[2]], //storing each image using nodelist index 
    buttonL = document.getElementById('bt1'),
    buttonR = document.getElementById('bt2'),
    index = 0;

slideList[0].style.display = 'block'; //first slide 

//function which display div to indicate what slide is showing
(function displayCircle() { 
    var circleContainer = document.getElementById('circleContainer'),
        circleHtml ='',
        i;
    for (i = 0; i < slideList.length; i++) {
        circleHtml += '<div class="circle"></div>';
    }
    circleContainer.innerHTML = circleHtml;
}());

circle[0].style.backgroundColor = 'red'; //first light

function slideIt(direction) {
    previous = index;

    if (direction == 'right') {
        index++;
        if (index >= slideList.length) {
            index = 0;
        }
    } else {
        index--;
        if (index < 0) {
            index = slideList.length-1;
        }
    }

    slideList[index].style.display = 'block'; 
    slideList[previous].style.display = 'none'; 

    circle[index].style.backgroundColor = 'red';
    circle[previous].style.backgroundColor = 'black';
}

buttonR.addEventListener('click', function(){ slideIt('right'); }, false);
buttonL.addEventListener('click', function(){ slideIt('left'); }, false);

关于javascript - 单击返回数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929796/

相关文章:

java - SPOJ 生命宇宙和一切

javascript - 多级 CSS 选择器

php - 将 html 响应放入 php 变量

javascript - 使用从 MongoDB JSON 对象获取 "Pretty"数据

arrays - 从 Parse 获取的数据未保存在数组中 - Swift 2.0

javascript - 图像未绘制在 Canvas 上 (HTML5)

javascript - Jquery点击打开模态返回 "undefined is not a function"

javascript - 我应该如何使用我的脚本来显示警报?

php - JSON - 使用 JS 搜索 Json 中字符串的值

php - 从表单发布数组