Me gustaría cambiar mis divs (estoy creando un estilo de carrusel div) con su nombre de clase . Así que me gustaría incrementar y disminuir (para ir a 'siguiente' y 'anterior') el número "box'1'" para cambiar entre ellos cada vez que hago clic en los botones, que contienen las funciones js
<div class="box1"> ... </div> <div class="box2"> ... </div> <div class="box3"> ... </div> <div class="box4"> ... </div>
Encontré algunas correcciones en este sitio, pero aún así no pude usarlas para mi código. Así que probé esto:
function increase() { var a = 1; var boxes = document.getElementById("box1"); boxes.value = a; a++; } function decrease() { var a = 1; var boxes = document.getElementById("box1"); boxes.value = a; a--; }
Y
<input class="buttongray" value="next" onclick="increase()"> <input class="buttonblue" value="back" onclick="decrease()">
let box = document.querySelectorAll('.box'); let ctr = 0; // onload fill box 1 box[ctr].style.display = "block"; box[ctr].innerHTML = "Box On " + (ctr+1); function ctrSwitch(n) { // int counter ctr += n; // counter check max and min ctr = (ctr>=box.length)? 0 : (ctr < 0) ? box.length-1: ctr; // loop and match active box by counter box.forEach((el, i) => { /* @param el = box[i] */ // option 1 (use ternary); // box[i].innerHTML = (ctr == i)? `Box On ${ctr+1}` : "..."; // option 2 (use if else); if ( ctr == i ) { el.style.display = "block"; el.innerHTML = `Box On ${ctr+1}`; } else { el.style.display = "none"; el.innerHTML = `...`; } }); }
.box { width: 50px; height: 50px; display: none; color: #fff; } .box1 { background: red; } .box2 { background: green; } .box3 { background: blue; } .box4 { background: purple; }
<div class="box box1"> ... </div> <div class="box box2"> ... </div> <div class="box box3"> ... </div> <div class="box box4"> ... </div> <button onclick="ctrSwitch(-1)">Prev</button> <button onclick="ctrSwitch(1)">Next</button>