【发布时间】:2017-07-19 20:45:20
【问题描述】:
我正在尝试制作简单的 JS 图片滑块。
到目前为止,我设法在存储在数组中的 div 元素上添加/删除“活动”类。
我的问题是,每当我在选定的特定 div 中添加或删除类时,其他人保持不变,直到函数出现在同一个 div 附近。
每当函数“indexPlus”触发时,我不知道如何检查其他 div 类。我正在考虑 for 循环中的一些内容:
for (var i = 0; i < pictures.length; i++) {
//here should be the code that checks other "inactive (divs that have class
//"picture active" but do not have the the same index as the selected
// picture)" divs
}
目前,我的代码运行正常,但并非以我希望的方式运行。我连续两天在谷歌上搜索并试图完成这项工作。也许我被错误的方向迷住了,没有以一种合乎逻辑的方式思考,我在 JS 是一个完全的菜鸟。随意更正我的代码和/或使其更有效率。对不起,我的英语不是我的母语。感谢您的时间和回答!
这是我的滑块 HTML 代码:
<div class="slider">
<div class="kontrola back">
<i class="fa fa-angle-left"></i>
</div>
<div class="picture" id="0" style="background-image: urlsomeUrl)">
</div>
<div class="picture" id="1" style="background-image: url(someUrl)">
</div>
<div class="picture" id="2" style="background-image: url(someUrl)">
</div>
<div class="picture" id="3" style="background-image: url(someUrl)">
</div>
<div class="picture" id="4" style="background-image: url(someUrl)">
</div>
<div class="kontrola next">
<i class="fa fa-angle-right"></i>
</div>
</div>
还有我的 JavaScript 代码:
var back = document.getElementsByClassName('back')[0];
var next = document.getElementsByClassName('next')[0];
var picturesArray = []; //creating array of pictures
//populating array by getting ids
for (var i = 0; i < 5; i++) {
picturesArray[i] = document.getElementById(i);
}
//setting the first picture
var index = 0;
var firstPicture = document.getElementById(index);
var class2 = firstPicture.className;
if(class2 == class2) {
firstPicture.className += " active";
} else {
firstPicture.className -= " active";
}
//function that executes on click of next button
function indexPlus() {
if (index >= picturesArray.length - 1) { //this resets the index
index = 0; //this resets the index
var activePicture = document.getElementById(index);
var class1 = activePicture.className;
if(class1 == "picture active") { //this checks class of the active picture
activePicture.classList.remove("active"); //this removes active class
} else {
activePicture.className += " active"; //this adds active class
}
} else {
index++;
var activePicture = document.getElementById(index);
var class1 = activePicture.className;
if(class1 == "picture active") {
activePicture.classList.remove("active");
} else {
activePicture.className += " active";
}
}
//before mentioned possible for loop
for (var i = 0; i < picturesArray.length; i++) {
//code...
}
}
//function that executes on click of back button
function indexMinus() {
}
//event listeners
back.addEventListener('click', indexMinus);
next.addEventListener('click', indexPlus);
【问题讨论】:
-
如果你使用 jQuery,你可以使用 .hasClass(),.addClass() 和 removClass() 方法。
-
@Prashanth 抱歉,我不能使用 jQuery。不过谢谢你的回答。
-
你能做一个小提琴吗?
-
@John 谢谢你的回答!虽然它没有直接解决我的问题,但它让我以更高级的方式思考。
标签: javascript html slider