如何做出这种逻辑

时间:2018-11-09 17:11:01

标签: javascript html dom

我在练习中遇到问题 enter image description here

到目前为止,我已经装箱了,但是javascript中的逻辑我不知道该怎么办?有什么建议吗?

这是我的进步:

enter image description here

代码非常简单:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>David Aparicio</title>
</head>
<body>
    <div class="container">
        <div class="box active">
    </div>

    <div class="box">
    </div>

    <div class="box">
    </div>        
</div>
<div class="buttons">
    <button> Left </button>
    <button> Right </button>
</div>

1 个答案:

答案 0 :(得分:0)

这是我的看法。

首先,我在您的按钮中添加了ID以引用它们。

<div class="buttons">
  <button id="left"> Left </button>
  <button id="right"> Right </button>
</div>

然后我的JavaScript如下:

//Find all boxes and put them in an array
let boxes = document.querySelectorAll(".box");
let activeIndex = 0;

function changeActive() {
  //remove previous active class
  document.querySelector(".active").classList.remove("active");

  //find box at active index and add active class
  document.querySelectorAll(".box")[activeIndex].classList.add("active");
}

//Event listeners to increment and decrement the active index

document.getElementById("left").addEventListener("click", function() {
  if(activeIndex > 0) {
    activeIndex -= 1;
    changeActive();
  }
});

document.getElementById("right").addEventListener("click", function() {
  if(activeIndex < boxes.length -1) {
    activeIndex += 1;
    changeActive();
  } 
});

JSFiddle:https://jsfiddle.net/r6foyj1d/13/

相关问题