При нажатии кнопки циклически переключайтесь между списком элементов div и переключайте видимость - PullRequest
0 голосов
/ 26 февраля 2020

У меня есть список div-ов (братьев и сестер). При загрузке страницы первый div отображается, а остальные скрыты. При нажатии кнопки мне нужен текущий видимый div, чтобы скрыть и следующий, чтобы показать. Как только последний элемент виден, когда нажимается кнопка, он должен l oop вернуться к первому элементу, который виден и скрывает последний элемент. Я не уверен, что правильный подход, но я почесал голову в этом в течение нескольких часов! Пожалуйста помоги! Код ниже того, что у меня так далеко. Активный класс будет иметь блок display: CSS. Все дивы отображаются: ни одного для начала.

 $('.hp-blurb').first().addClass('active');

 $('.red-btn').click(function() {

   $('.hp-blurb').removeClass('active');
   $('.hp-blurb').next().siblings().addClass('active');

});

Вот мой HTML:

<div class="red-btn">
  <img src="/red-btn.png" alt="red button" /> <spam class="red-btn-text" >PUSH ME</spam>
</div>
<div class="container">
  <div class="hp-blurb">                           
A gorilla has escaped from the ATLANTA zoo. An ENSEMBLE of zookeepers are trying to find it. In the event the gorilla SHOWS signs of fear it could attack.
  </div>
  <div class="hp-blurb">                           
A gorilla has escaped from the ATLANTA zoo. An ENSEMBLE of zookeepers are trying to find it. In the event the gorilla SHOWS signs of fear it could attack.
  </div>
  <div class="hp-blurb">                           
A gorilla has escaped from the ATLANTA zoo. An ENSEMBLE of zookeepers are trying to find it. In the event the gorilla SHOWS signs of fear it could attack.
  </div>
</div>

Ответы [ 3 ]

1 голос
/ 26 февраля 2020

Я создал скрипку для вашего решения: посмотрите ее @ https://jsfiddle.net/harshapache/89norsk6/

$('.hp-blurb').first().addClass('active');
  var totalHpBlurb = 0;
  $('.hp-blurb').each(function(){
  totalHpBlurb++;
  $(this).attr('data-index',totalHpBlurb);
});

 $('.red-btn').click(function() {
   var index = $('.hp-blurb.active').attr('data-index');
   $('.hp-blurb.active').removeClass('active');

   if(index < totalHpBlurb){
     index++;
     $('.hp-blurb[data-index="'+index+'"]').addClass('active');
   }else{
     $('.hp-blurb[data-index="1"]').addClass('active');
   }
 });
1 голос
/ 26 февраля 2020

Очень простой c раствор с ванилью JS:

function cycleVisibility(ev) {
  ev.preventDefault();

  // get a nodeList of all the divs
  const nlist = document.querySelectorAll('div.hp-blurb');

  for (let i = 0; i < nlist.length; i++) {

    // if div is active, that class name will be removed
    if (nlist[i].className.includes('active')) {
      nlist[i].classList.remove('active');

      // check wheter you're at the end of nodeList 
      const nextIndex = i < nlist.length - 1 ? i + 1 : 0;

      // and add the class that makes next (or first) div visible
      nlist[nextIndex].classList.add('active');

      // exit the loop
      break;
    }
  }
}

document.querySelector('div.hp-blurb').classList.add('active');
document.querySelector('div.red-btn').addEventListener('click', cycleVisibility, false);

А вот и JS Скрипка

1 голос
/ 26 февраля 2020

Как то так?

var normalDivs = [];
var focusDiv;

function loopThru(){
  focusDiv +=1;
  if (focusDiv > normalDivs.length-1){
    focusDiv = 0;
  }
  $('.normal').each(function(){
    $(this).css('visibility','hidden');
  });
  normalDivs[focusDiv].css('visibility','visible');
}

$(document).ready(function(){
  $('.normal').each(function(){
    normalDivs.push($(this));
  });
  focusDiv = 0;
  normalDivs[focusDiv].css('visibility','visible')
  $('.button').click(loopThru);
  
});
.normal, .button{
  user-select: none;
  background-color: red;
  color: white;
  display: inline-block;
  padding: 20px;
  font-size: 20px;
}

.normal{
  visibility: hidden;
}

.button{
  background-color: teal;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="normal">div 1</div>
<div class="normal">div 2</div>
<div class="normal">div 3</div>
<div class="normal">div 4</div>
<div class="normal">div 5</div>
<div class="normal">div 6</div>
<div class="button">button</div>
...