嗨,我正在尝试仅使用 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/